diff --git a/guide/src/class.md b/guide/src/class.md index 45718f5b667..c20cacd3cc7 100644 --- a/guide/src/class.md +++ b/guide/src/class.md @@ -412,10 +412,10 @@ impl SubSubClass { let base = PyClassInitializer::from(BaseClass::new()); let sub = base.add_subclass(SubClass { val2: val }); if val % 2 == 0 { - Ok(Py::new(py, sub)?.to_object(py)) + Ok(Py::new(py, sub)?.into_any()) } else { let sub_sub = sub.add_subclass(SubSubClass { val3: val }); - Ok(Py::new(py, sub_sub)?.to_object(py)) + Ok(Py::new(py, sub_sub)?.into_any()) } } } diff --git a/guide/src/conversions/traits.md b/guide/src/conversions/traits.md index fd9e90097f2..9f163df9ed2 100644 --- a/guide/src/conversions/traits.md +++ b/guide/src/conversions/traits.md @@ -294,8 +294,8 @@ enum RustyEnum<'py> { # fn main() -> PyResult<()> { # Python::with_gil(|py| -> PyResult<()> { # { -# let thing = 42_u8.to_object(py); -# let rust_thing: RustyEnum<'_> = thing.extract(py)?; +# let thing = 42_u8.into_pyobject(py)?; +# let rust_thing: RustyEnum<'_> = thing.extract()?; # # assert_eq!( # 42, @@ -318,8 +318,8 @@ enum RustyEnum<'py> { # ); # } # { -# let thing = (32_u8, 73_u8).to_object(py); -# let rust_thing: RustyEnum<'_> = thing.extract(py)?; +# let thing = (32_u8, 73_u8).into_pyobject(py)?; +# let rust_thing: RustyEnum<'_> = thing.extract()?; # # assert_eq!( # (32, 73), @@ -330,8 +330,8 @@ enum RustyEnum<'py> { # ); # } # { -# let thing = ("foo", 73_u8).to_object(py); -# let rust_thing: RustyEnum<'_> = thing.extract(py)?; +# let thing = ("foo", 73_u8).into_pyobject(py)?; +# let rust_thing: RustyEnum<'_> = thing.extract()?; # # assert_eq!( # (String::from("foo"), 73), @@ -427,8 +427,8 @@ enum RustyEnum { # fn main() -> PyResult<()> { # Python::with_gil(|py| -> PyResult<()> { # { -# let thing = 42_u8.to_object(py); -# let rust_thing: RustyEnum = thing.extract(py)?; +# let thing = 42_u8.into_pyobject(py)?; +# let rust_thing: RustyEnum = thing.extract()?; # # assert_eq!( # 42, @@ -440,8 +440,8 @@ enum RustyEnum { # } # # { -# let thing = "foo".to_object(py); -# let rust_thing: RustyEnum = thing.extract(py)?; +# let thing = "foo".into_pyobject(py)?; +# let rust_thing: RustyEnum = thing.extract()?; # # assert_eq!( # "foo", @@ -453,8 +453,8 @@ enum RustyEnum { # } # # { -# let thing = b"foo".to_object(py); -# let error = thing.extract::(py).unwrap_err(); +# let thing = b"foo".into_pyobject(py)?; +# let error = thing.extract::().unwrap_err(); # assert!(error.is_instance_of::(py)); # } # diff --git a/guide/src/migration.md b/guide/src/migration.md index 75b102d1c40..aeb7dcd0c2d 100644 --- a/guide/src/migration.md +++ b/guide/src/migration.md @@ -157,7 +157,7 @@ need to adapt an implementation of `IntoPyObject` to stay compatible with the Py Before: -```rust +```rust,ignore # use pyo3::prelude::*; # #[allow(dead_code)] struct MyPyObjectWrapper(PyObject); diff --git a/newsfragments/4595.changed.md b/newsfragments/4595.changed.md new file mode 100644 index 00000000000..e8b7eba5cbf --- /dev/null +++ b/newsfragments/4595.changed.md @@ -0,0 +1,2 @@ +- `PyErr::matches` is now fallible due to `IntoPyObject` migration. +- deprecate `ToPyObject` in favor of `IntoPyObject` \ No newline at end of file diff --git a/pytests/src/objstore.rs b/pytests/src/objstore.rs index 9a005c0ec97..844cee946ad 100644 --- a/pytests/src/objstore.rs +++ b/pytests/src/objstore.rs @@ -13,8 +13,8 @@ impl ObjStore { ObjStore::default() } - fn push(&mut self, py: Python<'_>, obj: &Bound<'_, PyAny>) { - self.obj.push(obj.to_object(py)); + fn push(&mut self, obj: &Bound<'_, PyAny>) { + self.obj.push(obj.clone().unbind()); } } diff --git a/src/conversion.rs b/src/conversion.rs index 3cc73072ed9..8847e377d9d 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -64,6 +64,10 @@ pub unsafe trait AsPyPointer { } /// Conversion trait that allows various objects to be converted into `PyObject`. +#[deprecated( + since = "0.23.0", + note = "`ToPyObject` is going to be replaced by `IntoPyObject`. See the migration guide for more information." +)] pub trait ToPyObject { /// Converts self into a Python object. fn to_object(&self, py: Python<'_>) -> PyObject; @@ -548,6 +552,7 @@ where /// Identity conversion: allows using existing `PyObject` instances where /// `T: ToPyObject` is expected. +#[allow(deprecated)] impl ToPyObject for &'_ T { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { diff --git a/src/conversions/chrono.rs b/src/conversions/chrono.rs index 7f36961b9ea..a4cfd89b8e0 100644 --- a/src/conversions/chrono.rs +++ b/src/conversions/chrono.rs @@ -20,23 +20,24 @@ //! //! ```rust //! use chrono::{DateTime, Duration, TimeZone, Utc}; -//! use pyo3::{Python, ToPyObject}; +//! use pyo3::{Python, PyResult, conversion::IntoPyObject, types::PyAnyMethods}; //! -//! fn main() { +//! fn main() -> PyResult<()> { //! pyo3::prepare_freethreaded_python(); //! Python::with_gil(|py| { //! // Build some chrono values //! let chrono_datetime = Utc.with_ymd_and_hms(2022, 1, 1, 12, 0, 0).unwrap(); //! let chrono_duration = Duration::seconds(1); //! // Convert them to Python -//! let py_datetime = chrono_datetime.to_object(py); -//! let py_timedelta = chrono_duration.to_object(py); +//! let py_datetime = chrono_datetime.into_pyobject(py)?; +//! let py_timedelta = chrono_duration.into_pyobject(py)?; //! // Do an operation in Python -//! let py_sum = py_datetime.call_method1(py, "__add__", (py_timedelta,)).unwrap(); +//! let py_sum = py_datetime.call_method1("__add__", (py_timedelta,))?; //! // Convert back to Rust -//! let chrono_sum: DateTime = py_sum.extract(py).unwrap(); +//! let chrono_sum: DateTime = py_sum.extract()?; //! println!("DateTime: {}", chrono_datetime); -//! }); +//! Ok(()) +//! }) //! } //! ``` @@ -53,9 +54,9 @@ use crate::types::{ timezone_utc, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyTime, PyTimeAccess, PyTzInfo, PyTzInfoAccess, }; -use crate::{ - ffi, Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{ffi, Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python}; #[cfg(Py_LIMITED_API)] use crate::{intern, DowncastError}; use chrono::offset::{FixedOffset, Utc}; @@ -63,6 +64,7 @@ use chrono::{ DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Offset, TimeZone, Timelike, }; +#[allow(deprecated)] impl ToPyObject for Duration { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -168,6 +170,7 @@ impl FromPyObject<'_> for Duration { } } +#[allow(deprecated)] impl ToPyObject for NaiveDate { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -233,6 +236,7 @@ impl FromPyObject<'_> for NaiveDate { } } +#[allow(deprecated)] impl ToPyObject for NaiveTime { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -308,6 +312,7 @@ impl FromPyObject<'_> for NaiveTime { } } +#[allow(deprecated)] impl ToPyObject for NaiveDateTime { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -395,6 +400,7 @@ impl FromPyObject<'_> for NaiveDateTime { } } +#[allow(deprecated)] impl ToPyObject for DateTime { fn to_object(&self, py: Python<'_>) -> PyObject { // FIXME: convert to better timezone representation here than just convert to fixed offset @@ -407,7 +413,7 @@ impl ToPyObject for DateTime { impl IntoPy for DateTime { fn into_py(self, py: Python<'_>) -> PyObject { - self.to_object(py) + self.into_pyobject(py).unwrap().into_any().unbind() } } @@ -491,6 +497,7 @@ impl FromPyObject<'py>> FromPyObject<'_> for DateTime) -> PyObject { @@ -574,6 +581,7 @@ impl FromPyObject<'_> for FixedOffset { } } +#[allow(deprecated)] impl ToPyObject for Utc { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -925,15 +933,15 @@ mod tests { } #[test] - fn test_pyo3_timedelta_topyobject() { + fn test_pyo3_timedelta_into_pyobject() { // Utility function used to check different durations. // The `name` parameter is used to identify the check in case of a failure. let check = |name: &'static str, delta: Duration, py_days, py_seconds, py_ms| { Python::with_gil(|py| { - let delta = delta.to_object(py); + let delta = delta.into_pyobject(py).unwrap(); let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms)); assert!( - delta.bind(py).eq(&py_delta).unwrap(), + delta.eq(&py_delta).unwrap(), "{}: {} != {}", name, delta, @@ -954,10 +962,10 @@ mod tests { let delta = Duration::seconds(86399999999999) + Duration::nanoseconds(999999000); // max check("delta max value", delta, 999999999, 86399, 999999); - // Also check that trying to convert an out of bound value panics. + // Also check that trying to convert an out of bound value errors. Python::with_gil(|py| { - assert!(panic::catch_unwind(|| Duration::min_value().to_object(py)).is_err()); - assert!(panic::catch_unwind(|| Duration::max_value().to_object(py)).is_err()); + assert!(Duration::min_value().into_pyobject(py).is_err()); + assert!(Duration::max_value().into_pyobject(py).is_err()); }); } @@ -1021,15 +1029,16 @@ mod tests { } #[test] - fn test_pyo3_date_topyobject() { + fn test_pyo3_date_into_pyobject() { let eq_ymd = |name: &'static str, year, month, day| { Python::with_gil(|py| { let date = NaiveDate::from_ymd_opt(year, month, day) .unwrap() - .to_object(py); + .into_pyobject(py) + .unwrap(); let py_date = new_py_datetime_ob(py, "date", (year, month, day)); assert_eq!( - date.bind(py).compare(&py_date).unwrap(), + date.compare(&py_date).unwrap(), Ordering::Equal, "{}: {} != {}", name, @@ -1063,7 +1072,7 @@ mod tests { } #[test] - fn test_pyo3_datetime_topyobject_utc() { + fn test_pyo3_datetime_into_pyobject_utc() { Python::with_gil(|py| { let check_utc = |name: &'static str, year, month, day, hour, minute, second, ms, py_ms| { @@ -1072,7 +1081,7 @@ mod tests { .and_hms_micro_opt(hour, minute, second, ms) .unwrap() .and_utc(); - let datetime = datetime.to_object(py); + let datetime = datetime.into_pyobject(py).unwrap(); let py_datetime = new_py_datetime_ob( py, "datetime", @@ -1088,7 +1097,7 @@ mod tests { ), ); assert_eq!( - datetime.bind(py).compare(&py_datetime).unwrap(), + datetime.compare(&py_datetime).unwrap(), Ordering::Equal, "{}: {} != {}", name, @@ -1112,7 +1121,7 @@ mod tests { } #[test] - fn test_pyo3_datetime_topyobject_fixed_offset() { + fn test_pyo3_datetime_into_pyobject_fixed_offset() { Python::with_gil(|py| { let check_fixed_offset = |name: &'static str, year, month, day, hour, minute, second, ms, py_ms| { @@ -1123,15 +1132,15 @@ mod tests { .unwrap() .and_local_timezone(offset) .unwrap(); - let datetime = datetime.to_object(py); - let py_tz = offset.to_object(py); + let datetime = datetime.into_pyobject(py).unwrap(); + let py_tz = offset.into_pyobject(py).unwrap(); let py_datetime = new_py_datetime_ob( py, "datetime", (year, month, day, hour, minute, second, py_ms, py_tz), ); assert_eq!( - datetime.bind(py).compare(&py_datetime).unwrap(), + datetime.compare(&py_datetime).unwrap(), Ordering::Equal, "{}: {} != {}", name, @@ -1191,7 +1200,7 @@ mod tests { let second = 9; let micro = 999_999; let offset = FixedOffset::east_opt(3600).unwrap(); - let py_tz = offset.to_object(py); + let py_tz = offset.into_pyobject(py).unwrap(); let py_datetime = new_py_datetime_ob( py, "datetime", @@ -1224,21 +1233,27 @@ mod tests { } #[test] - fn test_pyo3_offset_fixed_topyobject() { + fn test_pyo3_offset_fixed_into_pyobject() { Python::with_gil(|py| { // Chrono offset - let offset = FixedOffset::east_opt(3600).unwrap().to_object(py); + let offset = FixedOffset::east_opt(3600) + .unwrap() + .into_pyobject(py) + .unwrap(); // Python timezone from timedelta let td = new_py_datetime_ob(py, "timedelta", (0, 3600, 0)); let py_timedelta = new_py_datetime_ob(py, "timezone", (td,)); // Should be equal - assert!(offset.bind(py).eq(py_timedelta).unwrap()); + assert!(offset.eq(py_timedelta).unwrap()); // Same but with negative values - let offset = FixedOffset::east_opt(-3600).unwrap().to_object(py); + let offset = FixedOffset::east_opt(-3600) + .unwrap() + .into_pyobject(py) + .unwrap(); let td = new_py_datetime_ob(py, "timedelta", (0, -3600, 0)); let py_timedelta = new_py_datetime_ob(py, "timezone", (td,)); - assert!(offset.bind(py).eq(py_timedelta).unwrap()); + assert!(offset.eq(py_timedelta).unwrap()); }) } @@ -1253,11 +1268,11 @@ mod tests { } #[test] - fn test_pyo3_offset_utc_topyobject() { + fn test_pyo3_offset_utc_into_pyobject() { Python::with_gil(|py| { - let utc = Utc.to_object(py); + let utc = Utc.into_pyobject(py).unwrap(); let py_utc = python_utc(py); - assert!(utc.bind(py).is(&py_utc)); + assert!(utc.is(&py_utc)); }) } @@ -1280,15 +1295,16 @@ mod tests { } #[test] - fn test_pyo3_time_topyobject() { + fn test_pyo3_time_into_pyobject() { Python::with_gil(|py| { let check_time = |name: &'static str, hour, minute, second, ms, py_ms| { let time = NaiveTime::from_hms_micro_opt(hour, minute, second, ms) .unwrap() - .to_object(py); + .into_pyobject(py) + .unwrap(); let py_time = new_py_datetime_ob(py, "time", (hour, minute, second, py_ms)); assert!( - time.bind(py).eq(&py_time).unwrap(), + time.eq(&py_time).unwrap(), "{}: {} != {}", name, time, @@ -1420,8 +1436,8 @@ mod tests { // We use to `from_ymd_opt` constructor so that we only test valid `NaiveDate`s. // This is to skip the test if we are creating an invalid date, like February 31. if let Some(date) = NaiveDate::from_ymd_opt(year, month, day) { - let py_date = date.to_object(py); - let roundtripped: NaiveDate = py_date.extract(py).expect("Round trip"); + let py_date = date.into_pyobject(py).unwrap(); + let roundtripped: NaiveDate = py_date.extract().expect("Round trip"); assert_eq!(date, roundtripped); } }) @@ -1441,8 +1457,8 @@ mod tests { Python::with_gil(|py| { if let Some(time) = NaiveTime::from_hms_micro_opt(hour, min, sec, micro) { // Wrap in CatchWarnings to avoid to_object firing warning for truncated leap second - let py_time = CatchWarnings::enter(py, |_| Ok(time.to_object(py))).unwrap(); - let roundtripped: NaiveTime = py_time.extract(py).expect("Round trip"); + let py_time = CatchWarnings::enter(py, |_| time.into_pyobject(py)).unwrap(); + let roundtripped: NaiveTime = py_time.extract().expect("Round trip"); // Leap seconds are not roundtripped let expected_roundtrip_time = micro.checked_sub(1_000_000).map(|micro| NaiveTime::from_hms_micro_opt(hour, min, sec, micro).unwrap()).unwrap_or(time); assert_eq!(expected_roundtrip_time, roundtripped); @@ -1465,8 +1481,8 @@ mod tests { let time_opt = NaiveTime::from_hms_micro_opt(hour, min, sec, micro); if let (Some(date), Some(time)) = (date_opt, time_opt) { let dt = NaiveDateTime::new(date, time); - let pydt = dt.to_object(py); - let roundtripped: NaiveDateTime = pydt.extract(py).expect("Round trip"); + let pydt = dt.into_pyobject(py).unwrap(); + let roundtripped: NaiveDateTime = pydt.extract().expect("Round trip"); assert_eq!(dt, roundtripped); } }) diff --git a/src/conversions/chrono_tz.rs b/src/conversions/chrono_tz.rs index 91428638f1e..2dc68218f06 100644 --- a/src/conversions/chrono_tz.rs +++ b/src/conversions/chrono_tz.rs @@ -21,16 +21,17 @@ //! //! ```rust,no_run //! use chrono_tz::Tz; -//! use pyo3::{Python, ToPyObject}; +//! use pyo3::{Python, PyResult, conversion::IntoPyObject, types::PyAnyMethods}; //! -//! fn main() { +//! fn main() -> PyResult<()> { //! pyo3::prepare_freethreaded_python(); //! Python::with_gil(|py| { //! // Convert to Python -//! let py_tzinfo = Tz::Europe__Paris.to_object(py); +//! let py_tzinfo = Tz::Europe__Paris.into_pyobject(py)?; //! // Convert back to Rust -//! assert_eq!(py_tzinfo.extract::(py).unwrap(), Tz::Europe__Paris); -//! }); +//! assert_eq!(py_tzinfo.extract::()?, Tz::Europe__Paris); +//! Ok(()) +//! }) //! } //! ``` use crate::conversion::IntoPyObject; @@ -38,12 +39,13 @@ use crate::exceptions::PyValueError; use crate::pybacked::PyBackedStr; use crate::sync::GILOnceCell; use crate::types::{any::PyAnyMethods, PyType}; -use crate::{ - intern, Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{intern, Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python}; use chrono_tz::Tz; use std::str::FromStr; +#[allow(deprecated)] impl ToPyObject for Tz { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -112,19 +114,19 @@ mod tests { } #[test] - fn test_topyobject() { + fn test_into_pyobject() { Python::with_gil(|py| { - let assert_eq = |l: PyObject, r: Bound<'_, PyAny>| { - assert!(l.bind(py).eq(r).unwrap()); + let assert_eq = |l: Bound<'_, PyAny>, r: Bound<'_, PyAny>| { + assert!(l.eq(r).unwrap()); }; assert_eq( - Tz::Europe__Paris.to_object(py), + Tz::Europe__Paris.into_pyobject(py).unwrap(), new_zoneinfo(py, "Europe/Paris"), ); - assert_eq(Tz::UTC.to_object(py), new_zoneinfo(py, "UTC")); + assert_eq(Tz::UTC.into_pyobject(py).unwrap(), new_zoneinfo(py, "UTC")); assert_eq( - Tz::Etc__GMTMinus5.to_object(py), + Tz::Etc__GMTMinus5.into_pyobject(py).unwrap(), new_zoneinfo(py, "Etc/GMT-5"), ); }); diff --git a/src/conversions/either.rs b/src/conversions/either.rs index 43822347c81..ec0b7e49d96 100644 --- a/src/conversions/either.rs +++ b/src/conversions/either.rs @@ -26,18 +26,19 @@ //! //! ```rust //! use either::Either; -//! use pyo3::{Python, ToPyObject}; +//! use pyo3::{Python, PyResult, conversion::IntoPyObject, types::PyAnyMethods}; //! -//! fn main() { +//! fn main() -> PyResult<()> { //! pyo3::prepare_freethreaded_python(); //! Python::with_gil(|py| { //! // Create a string and an int in Python. -//! let py_str = "crab".to_object(py); -//! let py_int = 42.to_object(py); +//! let py_str = "crab".into_pyobject(py)?; +//! let py_int = 42i32.into_pyobject(py)?; //! // Now convert it to an Either. -//! let either_str: Either = py_str.extract(py).unwrap(); -//! let either_int: Either = py_int.extract(py).unwrap(); -//! }); +//! let either_str: Either = py_str.extract()?; +//! let either_int: Either = py_int.extract()?; +//! Ok(()) +//! }) //! } //! ``` //! @@ -45,9 +46,11 @@ #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, exceptions::PyTypeError, types::any::PyAnyMethods, Bound, - BoundObject, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, + BoundObject, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, }; use either::Either; @@ -119,6 +122,7 @@ where } #[cfg_attr(docsrs, doc(cfg(feature = "either")))] +#[allow(deprecated)] impl ToPyObject for Either where L: ToPyObject, @@ -168,8 +172,10 @@ mod tests { use std::borrow::Cow; use crate::exceptions::PyTypeError; - use crate::{Python, ToPyObject}; + use crate::Python; + use crate::prelude::IntoPyObject; + use crate::types::PyAnyMethods; use either::Either; #[test] @@ -180,30 +186,30 @@ mod tests { Python::with_gil(|py| { let l = E::Left(42); - let obj_l = l.to_object(py); - assert_eq!(obj_l.extract::(py).unwrap(), 42); - assert_eq!(obj_l.extract::(py).unwrap(), l); + let obj_l = (&l).into_pyobject(py).unwrap(); + assert_eq!(obj_l.extract::().unwrap(), 42); + assert_eq!(obj_l.extract::().unwrap(), l); let r = E::Right("foo".to_owned()); - let obj_r = r.to_object(py); - assert_eq!(obj_r.extract::>(py).unwrap(), "foo"); - assert_eq!(obj_r.extract::(py).unwrap(), r); + let obj_r = (&r).into_pyobject(py).unwrap(); + assert_eq!(obj_r.extract::>().unwrap(), "foo"); + assert_eq!(obj_r.extract::().unwrap(), r); - let obj_s = "foo".to_object(py); - let err = obj_s.extract::(py).unwrap_err(); + let obj_s = "foo".into_pyobject(py).unwrap(); + let err = obj_s.extract::().unwrap_err(); assert!(err.is_instance_of::(py)); assert_eq!( err.to_string(), "TypeError: failed to convert the value to 'Union[i32, f32]'" ); - let obj_i = 42.to_object(py); - assert_eq!(obj_i.extract::(py).unwrap(), E1::Left(42)); - assert_eq!(obj_i.extract::(py).unwrap(), E2::Left(42.0)); + let obj_i = 42i32.into_pyobject(py).unwrap(); + assert_eq!(obj_i.extract::().unwrap(), E1::Left(42)); + assert_eq!(obj_i.extract::().unwrap(), E2::Left(42.0)); - let obj_f = 42.0.to_object(py); - assert_eq!(obj_f.extract::(py).unwrap(), E1::Right(42.0)); - assert_eq!(obj_f.extract::(py).unwrap(), E2::Left(42.0)); + let obj_f = 42.0f64.into_pyobject(py).unwrap(); + assert_eq!(obj_f.extract::().unwrap(), E1::Right(42.0)); + assert_eq!(obj_f.extract::().unwrap(), E2::Left(42.0)); }); } } diff --git a/src/conversions/hashbrown.rs b/src/conversions/hashbrown.rs index db42075adeb..25ec014341e 100644 --- a/src/conversions/hashbrown.rs +++ b/src/conversions/hashbrown.rs @@ -16,6 +16,8 @@ //! //! Note that you must use compatible versions of hashbrown and PyO3. //! The required hashbrown version may vary based on the version of PyO3. +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, types::{ @@ -25,10 +27,11 @@ use crate::{ set::{new_from_iter, try_new_from_iter, PySetMethods}, PyDict, PyFrozenSet, PySet, }, - Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, + Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, }; use std::{cmp, hash}; +#[allow(deprecated)] impl ToPyObject for hashbrown::HashMap where K: hash::Hash + cmp::Eq + ToPyObject, @@ -113,6 +116,7 @@ where } } +#[allow(deprecated)] impl ToPyObject for hashbrown::HashSet where T: hash::Hash + Eq + ToPyObject, @@ -194,8 +198,7 @@ mod tests { let mut map = hashbrown::HashMap::::new(); map.insert(1, 1); - let m = map.to_object(py); - let py_map = m.downcast_bound::(py).unwrap(); + let py_map = (&map).into_pyobject(py).unwrap(); assert!(py_map.len() == 1); assert!( diff --git a/src/conversions/indexmap.rs b/src/conversions/indexmap.rs index acb466c3d0a..638d303e37a 100644 --- a/src/conversions/indexmap.rs +++ b/src/conversions/indexmap.rs @@ -89,9 +89,12 @@ use crate::conversion::IntoPyObject; use crate::types::*; -use crate::{Bound, FromPyObject, IntoPy, PyErr, PyObject, Python, ToPyObject}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{Bound, FromPyObject, IntoPy, PyErr, PyObject, Python}; use std::{cmp, hash}; +#[allow(deprecated)] impl ToPyObject for indexmap::IndexMap where K: hash::Hash + cmp::Eq + ToPyObject, @@ -179,8 +182,9 @@ where #[cfg(test)] mod test_indexmap { + use crate::prelude::IntoPyObject; use crate::types::*; - use crate::{IntoPy, PyObject, Python, ToPyObject}; + use crate::{IntoPy, PyObject, Python}; #[test] fn test_indexmap_indexmap_to_python() { @@ -188,8 +192,7 @@ mod test_indexmap { let mut map = indexmap::IndexMap::::new(); map.insert(1, 1); - let m = map.to_object(py); - let py_map = m.downcast_bound::(py).unwrap(); + let py_map = (&map).into_pyobject(py).unwrap(); assert!(py_map.len() == 1); assert!( diff --git a/src/conversions/num_bigint.rs b/src/conversions/num_bigint.rs index e05a807bb2c..df8e108776f 100644 --- a/src/conversions/num_bigint.rs +++ b/src/conversions/num_bigint.rs @@ -49,12 +49,14 @@ #[cfg(Py_LIMITED_API)] use crate::types::{bytes::PyBytesMethods, PyBytes}; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, ffi, instance::Bound, types::{any::PyAnyMethods, PyInt}, - FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, + FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, }; use num_bigint::{BigInt, BigUint}; @@ -66,6 +68,7 @@ use num_bigint::Sign; macro_rules! bigint_conversion { ($rust_ty: ty, $is_signed: literal, $to_bytes: path) => { #[cfg_attr(docsrs, doc(cfg(feature = "num-bigint")))] + #[allow(deprecated)] impl ToPyObject for $rust_ty { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -355,11 +358,11 @@ mod tests { }) } - fn python_fib(py: Python<'_>) -> impl Iterator + '_ { - let mut f0 = 1.to_object(py); - let mut f1 = 1.to_object(py); + fn python_fib(py: Python<'_>) -> impl Iterator> + '_ { + let mut f0 = 1i32.into_pyobject(py).unwrap().into_any(); + let mut f1 = 1i32.into_pyobject(py).unwrap().into_any(); std::iter::from_fn(move || { - let f2 = f0.call_method1(py, "__add__", (f1.bind(py),)).unwrap(); + let f2 = f0.call_method1("__add__", (&f1,)).unwrap(); Some(std::mem::replace(&mut f0, std::mem::replace(&mut f1, f2))) }) } @@ -370,9 +373,9 @@ mod tests { // check the first 2000 numbers in the fibonacci sequence for (py_result, rs_result) in python_fib(py).zip(rust_fib::()).take(2000) { // Python -> Rust - assert_eq!(py_result.extract::(py).unwrap(), rs_result); + assert_eq!(py_result.extract::().unwrap(), rs_result); // Rust -> Python - assert!(py_result.bind(py).eq(rs_result).unwrap()); + assert!(py_result.eq(rs_result).unwrap()); } }); } @@ -383,19 +386,19 @@ mod tests { // check the first 2000 numbers in the fibonacci sequence for (py_result, rs_result) in python_fib(py).zip(rust_fib::()).take(2000) { // Python -> Rust - assert_eq!(py_result.extract::(py).unwrap(), rs_result); + assert_eq!(py_result.extract::().unwrap(), rs_result); // Rust -> Python - assert!(py_result.bind(py).eq(&rs_result).unwrap()); + assert!(py_result.eq(&rs_result).unwrap()); // negate let rs_result = rs_result * -1; - let py_result = py_result.call_method0(py, "__neg__").unwrap(); + let py_result = py_result.call_method0("__neg__").unwrap(); // Python -> Rust - assert_eq!(py_result.extract::(py).unwrap(), rs_result); + assert_eq!(py_result.extract::().unwrap(), rs_result); // Rust -> Python - assert!(py_result.bind(py).eq(rs_result).unwrap()); + assert!(py_result.eq(rs_result).unwrap()); } }); } @@ -435,7 +438,7 @@ mod tests { #[test] fn handle_zero() { Python::with_gil(|py| { - let zero: BigInt = 0.to_object(py).extract(py).unwrap(); + let zero: BigInt = 0i32.into_pyobject(py).unwrap().extract().unwrap(); assert_eq!(zero, BigInt::from(0)); }) } diff --git a/src/conversions/num_complex.rs b/src/conversions/num_complex.rs index bf28aa73932..58dc65df32e 100644 --- a/src/conversions/num_complex.rs +++ b/src/conversions/num_complex.rs @@ -93,11 +93,13 @@ //! result = get_eigenvalues(m11,m12,m21,m22) //! assert result == [complex(1,-1), complex(-2,0)] //! ``` +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, types::{any::PyAnyMethods, PyComplex}, - Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, + Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python, }; use num_complex::Complex; use std::os::raw::c_double; @@ -119,6 +121,7 @@ impl PyComplex { macro_rules! complex_conversion { ($float: ty) => { #[cfg_attr(docsrs, doc(cfg(feature = "num-complex")))] + #[allow(deprecated)] impl ToPyObject for Complex<$float> { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -216,6 +219,7 @@ complex_conversion!(f64); #[cfg(test)] mod tests { use super::*; + use crate::prelude::IntoPyObject; use crate::tests::common::generate_unique_module_name; use crate::types::{complex::PyComplexMethods, PyModule}; use pyo3_ffi::c_str; @@ -232,16 +236,16 @@ mod tests { #[test] fn to_from_complex() { Python::with_gil(|py| { - let val = Complex::new(3.0, 1.2); - let obj = val.to_object(py); - assert_eq!(obj.extract::>(py).unwrap(), val); + let val = Complex::new(3.0f64, 1.2); + let obj = val.into_pyobject(py).unwrap(); + assert_eq!(obj.extract::>().unwrap(), val); }); } #[test] fn from_complex_err() { Python::with_gil(|py| { - let obj = vec![1].to_object(py); - assert!(obj.extract::>(py).is_err()); + let obj = vec![1i32].into_pyobject(py).unwrap(); + assert!(obj.extract::>().is_err()); }); } #[test] diff --git a/src/conversions/num_rational.rs b/src/conversions/num_rational.rs index 2448ad3701e..cda877502b3 100644 --- a/src/conversions/num_rational.rs +++ b/src/conversions/num_rational.rs @@ -48,9 +48,9 @@ use crate::ffi; use crate::sync::GILOnceCell; use crate::types::any::PyAnyMethods; use crate::types::PyType; -use crate::{ - Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python}; #[cfg(feature = "num-bigint")] use num_bigint::BigInt; @@ -84,6 +84,7 @@ macro_rules! rational_conversion { } } + #[allow(deprecated)] impl ToPyObject for Ratio<$int> { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { diff --git a/src/conversions/rust_decimal.rs b/src/conversions/rust_decimal.rs index c353eb91d8a..7926592119a 100644 --- a/src/conversions/rust_decimal.rs +++ b/src/conversions/rust_decimal.rs @@ -55,9 +55,9 @@ use crate::sync::GILOnceCell; use crate::types::any::PyAnyMethods; use crate::types::string::PyStringMethods; use crate::types::PyType; -use crate::{ - Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{Bound, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python}; use rust_decimal::Decimal; use std::str::FromStr; @@ -82,6 +82,7 @@ fn get_decimal_cls(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> { DECIMAL_CLS.import(py, "decimal", "Decimal") } +#[allow(deprecated)] impl ToPyObject for Decimal { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { diff --git a/src/conversions/smallvec.rs b/src/conversions/smallvec.rs index be90113344e..b914d7e0f49 100644 --- a/src/conversions/smallvec.rs +++ b/src/conversions/smallvec.rs @@ -23,12 +23,14 @@ use crate::types::any::PyAnyMethods; use crate::types::list::new_from_iter; use crate::types::{PySequence, PyString}; use crate::PyErr; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ err::DowncastError, ffi, Bound, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, - ToPyObject, }; use smallvec::{Array, SmallVec}; +#[allow(deprecated)] impl ToPyObject for SmallVec where A: Array, @@ -167,10 +169,10 @@ mod tests { } #[test] - fn test_smallvec_to_object() { + fn test_smallvec_into_pyobject() { Python::with_gil(|py| { let sv: SmallVec<[u64; 8]> = [1, 2, 3, 4, 5].iter().cloned().collect(); - let hso: PyObject = sv.to_object(py); + let hso = sv.into_pyobject(py).unwrap(); let l = PyList::new(py, [1, 2, 3, 4, 5]).unwrap(); assert!(l.eq(hso).unwrap()); }); diff --git a/src/conversions/std/array.rs b/src/conversions/std/array.rs index 5a07b224c5b..c184aa7f732 100644 --- a/src/conversions/std/array.rs +++ b/src/conversions/std/array.rs @@ -2,10 +2,9 @@ use crate::conversion::IntoPyObject; use crate::instance::Bound; use crate::types::any::PyAnyMethods; use crate::types::PySequence; -use crate::{ - err::DowncastError, ffi, FromPyObject, IntoPy, Py, PyAny, PyObject, PyResult, Python, - ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{err::DowncastError, ffi, FromPyObject, IntoPy, Py, PyAny, PyObject, PyResult, Python}; use crate::{exceptions, PyErr}; impl IntoPy for [T; N] @@ -69,6 +68,7 @@ where } } +#[allow(deprecated)] impl ToPyObject for [T; N] where T: ToPyObject, @@ -168,7 +168,7 @@ mod tests { ffi, types::{any::PyAnyMethods, PyBytes, PyBytesMethods}, }; - use crate::{types::PyList, IntoPy, PyResult, Python, ToPyObject}; + use crate::{types::PyList, IntoPy, PyResult, Python}; #[test] fn array_try_from_fn() { @@ -219,11 +219,11 @@ mod tests { }); } #[test] - fn test_topyobject_array_conversion() { + fn test_into_pyobject_array_conversion() { Python::with_gil(|py| { let array: [f32; 4] = [0.0, -16.0, 16.0, 42.0]; - let pyobject = array.to_object(py); - let pylist = pyobject.downcast_bound::(py).unwrap(); + let pyobject = array.into_pyobject(py).unwrap(); + let pylist = pyobject.downcast::().unwrap(); assert_eq!(pylist.get_item(0).unwrap().extract::().unwrap(), 0.0); assert_eq!(pylist.get_item(1).unwrap().extract::().unwrap(), -16.0); assert_eq!(pylist.get_item(2).unwrap().extract::().unwrap(), 16.0); diff --git a/src/conversions/std/cell.rs b/src/conversions/std/cell.rs index 75a8a13a787..8c8149b4a57 100644 --- a/src/conversions/std/cell.rs +++ b/src/conversions/std/cell.rs @@ -2,10 +2,11 @@ use std::cell::Cell; use crate::{ conversion::IntoPyObject, types::any::PyAnyMethods, Bound, FromPyObject, IntoPy, PyAny, - PyObject, PyResult, Python, ToPyObject, + PyObject, PyResult, Python, }; -impl ToPyObject for Cell { +#[allow(deprecated)] +impl crate::ToPyObject for Cell { fn to_object(&self, py: Python<'_>) -> PyObject { self.get().to_object(py) } diff --git a/src/conversions/std/ipaddr.rs b/src/conversions/std/ipaddr.rs index bff81ad1a1f..6c5e74d4881 100755 --- a/src/conversions/std/ipaddr.rs +++ b/src/conversions/std/ipaddr.rs @@ -7,9 +7,9 @@ use crate::sync::GILOnceCell; use crate::types::any::PyAnyMethods; use crate::types::string::PyStringMethods; use crate::types::PyType; -use crate::{ - intern, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{intern, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python}; impl FromPyObject<'_> for IpAddr { fn extract_bound(obj: &Bound<'_, PyAny>) -> PyResult { @@ -31,6 +31,7 @@ impl FromPyObject<'_> for IpAddr { } } +#[allow(deprecated)] impl ToPyObject for Ipv4Addr { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -62,6 +63,7 @@ impl<'py> IntoPyObject<'py> for &Ipv4Addr { } } +#[allow(deprecated)] impl ToPyObject for Ipv6Addr { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -93,6 +95,7 @@ impl<'py> IntoPyObject<'py> for &Ipv6Addr { } } +#[allow(deprecated)] impl ToPyObject for IpAddr { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -168,11 +171,11 @@ mod test_ipaddr { fn test_from_pystring() { Python::with_gil(|py| { let py_str = PyString::new(py, "0:0:0:0:0:0:0:1"); - let ip: IpAddr = py_str.to_object(py).extract(py).unwrap(); + let ip: IpAddr = py_str.extract().unwrap(); assert_eq!(ip, IpAddr::from_str("::1").unwrap()); let py_str = PyString::new(py, "invalid"); - assert!(py_str.to_object(py).extract::(py).is_err()); + assert!(py_str.extract::().is_err()); }); } } diff --git a/src/conversions/std/map.rs b/src/conversions/std/map.rs index 582c56b613f..888bd13c180 100644 --- a/src/conversions/std/map.rs +++ b/src/conversions/std/map.rs @@ -2,13 +2,16 @@ use std::{cmp, collections, hash}; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, instance::Bound, types::{any::PyAnyMethods, dict::PyDictMethods, PyDict}, - FromPyObject, IntoPy, PyAny, PyErr, PyObject, Python, ToPyObject, + FromPyObject, IntoPy, PyAny, PyErr, PyObject, Python, }; +#[allow(deprecated)] impl ToPyObject for collections::HashMap where K: hash::Hash + cmp::Eq + ToPyObject, @@ -24,6 +27,7 @@ where } } +#[allow(deprecated)] impl ToPyObject for collections::BTreeMap where K: cmp::Eq + ToPyObject, @@ -203,8 +207,7 @@ mod tests { let mut map = HashMap::::new(); map.insert(1, 1); - let m = map.to_object(py); - let py_map = m.downcast_bound::(py).unwrap(); + let py_map = (&map).into_pyobject(py).unwrap(); assert!(py_map.len() == 1); assert!( @@ -226,8 +229,7 @@ mod tests { let mut map = BTreeMap::::new(); map.insert(1, 1); - let m = map.to_object(py); - let py_map = m.downcast_bound::(py).unwrap(); + let py_map = (&map).into_pyobject(py).unwrap(); assert!(py_map.len() == 1); assert!( diff --git a/src/conversions/std/num.rs b/src/conversions/std/num.rs index 80bc678fddf..04d6afe887e 100644 --- a/src/conversions/std/num.rs +++ b/src/conversions/std/num.rs @@ -5,9 +5,10 @@ use crate::ffi_ptr_ext::FfiPtrExt; use crate::inspect::types::TypeInfo; use crate::types::any::PyAnyMethods; use crate::types::{PyBytes, PyInt}; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ exceptions, ffi, Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, - ToPyObject, }; use std::convert::Infallible; use std::num::{ @@ -18,6 +19,7 @@ use std::os::raw::c_long; macro_rules! int_fits_larger_int { ($rust_type:ty, $larger_type:ty) => { + #[allow(deprecated)] impl ToPyObject for $rust_type { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -98,6 +100,7 @@ macro_rules! extract_int { macro_rules! int_convert_u64_or_i64 { ($rust_type:ty, $pylong_from_ll_or_ull:expr, $pylong_as_ll_or_ull:expr, $force_index_call:literal) => { + #[allow(deprecated)] impl ToPyObject for $rust_type { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -153,6 +156,7 @@ macro_rules! int_convert_u64_or_i64 { macro_rules! int_fits_c_long { ($rust_type:ty) => { + #[allow(deprecated)] impl ToPyObject for $rust_type { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -211,6 +215,7 @@ macro_rules! int_fits_c_long { }; } +#[allow(deprecated)] impl ToPyObject for u8 { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -328,6 +333,7 @@ mod fast_128bit_int_conversion { // for 128bit Integers macro_rules! int_convert_128 { ($rust_type: ty, $is_signed: literal) => { + #[allow(deprecated)] impl ToPyObject for $rust_type { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -474,6 +480,7 @@ mod slow_128bit_int_conversion { // for 128bit Integers macro_rules! int_convert_128 { ($rust_type: ty, $half_type: ty) => { + #[allow(deprecated)] impl ToPyObject for $rust_type { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -571,6 +578,7 @@ fn err_if_invalid_value( macro_rules! nonzero_int_impl { ($nonzero_type:ty, $primitive_type:ty) => { + #[allow(deprecated)] impl ToPyObject for $nonzero_type { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -717,10 +725,10 @@ mod test_128bit_integers { fn test_i128_max() { Python::with_gil(|py| { let v = i128::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert_eq!(v as u128, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert_eq!(v as u128, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }) } @@ -728,10 +736,10 @@ mod test_128bit_integers { fn test_i128_min() { Python::with_gil(|py| { let v = i128::MIN; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); + assert!(obj.extract::().is_err()); }) } @@ -739,9 +747,9 @@ mod test_128bit_integers { fn test_u128_max() { Python::with_gil(|py| { let v = u128::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }) } @@ -767,13 +775,13 @@ mod test_128bit_integers { fn test_nonzero_i128_max() { Python::with_gil(|py| { let v = NonZeroI128::new(i128::MAX).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); assert_eq!( NonZeroU128::new(v.get() as u128).unwrap(), - obj.extract::(py).unwrap() + obj.extract::().unwrap() ); - assert!(obj.extract::(py).is_err()); + assert!(obj.extract::().is_err()); }) } @@ -781,10 +789,10 @@ mod test_128bit_integers { fn test_nonzero_i128_min() { Python::with_gil(|py| { let v = NonZeroI128::new(i128::MIN).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); + assert!(obj.extract::().is_err()); }) } @@ -792,9 +800,9 @@ mod test_128bit_integers { fn test_nonzero_u128_max() { Python::with_gil(|py| { let v = NonZeroU128::new(u128::MAX).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }) } @@ -837,18 +845,19 @@ mod test_128bit_integers { #[cfg(test)] mod tests { + use crate::prelude::IntoPyObject; + use crate::types::PyAnyMethods; use crate::Python; - use crate::ToPyObject; use std::num::*; #[test] fn test_u32_max() { Python::with_gil(|py| { let v = u32::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert_eq!(u64::from(v), obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert_eq!(u64::from(v), obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }); } @@ -856,10 +865,10 @@ mod tests { fn test_i64_max() { Python::with_gil(|py| { let v = i64::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert_eq!(v as u64, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert_eq!(v as u64, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }); } @@ -867,10 +876,10 @@ mod tests { fn test_i64_min() { Python::with_gil(|py| { let v = i64::MIN; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); + assert!(obj.extract::().is_err()); }); } @@ -878,9 +887,9 @@ mod tests { fn test_u64_max() { Python::with_gil(|py| { let v = u64::MAX; - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }); } @@ -888,14 +897,15 @@ mod tests { ($test_mod_name:ident, $t:ty) => ( mod $test_mod_name { use crate::exceptions; - use crate::ToPyObject; + use crate::conversion::IntoPyObject; + use crate::types::PyAnyMethods; use crate::Python; #[test] fn from_py_string_type_error() { Python::with_gil(|py| { - let obj = ("123").to_object(py); - let err = obj.extract::<$t>(py).unwrap_err(); + let obj = ("123").into_pyobject(py).unwrap(); + let err = obj.extract::<$t>().unwrap_err(); assert!(err.is_instance_of::(py)); }); } @@ -903,8 +913,8 @@ mod tests { #[test] fn from_py_float_type_error() { Python::with_gil(|py| { - let obj = (12.3).to_object(py); - let err = obj.extract::<$t>(py).unwrap_err(); + let obj = (12.3f64).into_pyobject(py).unwrap(); + let err = obj.extract::<$t>().unwrap_err(); assert!(err.is_instance_of::(py));}); } @@ -912,8 +922,8 @@ mod tests { fn to_py_object_and_back() { Python::with_gil(|py| { let val = 123 as $t; - let obj = val.to_object(py); - assert_eq!(obj.extract::<$t>(py).unwrap(), val as $t);}); + let obj = val.into_pyobject(py).unwrap(); + assert_eq!(obj.extract::<$t>().unwrap(), val as $t);}); } } ) @@ -936,10 +946,10 @@ mod tests { fn test_nonzero_u32_max() { Python::with_gil(|py| { let v = NonZeroU32::new(u32::MAX).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert_eq!(NonZeroU64::from(v), obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert_eq!(NonZeroU64::from(v), obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }); } @@ -947,13 +957,13 @@ mod tests { fn test_nonzero_i64_max() { Python::with_gil(|py| { let v = NonZeroI64::new(i64::MAX).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); assert_eq!( NonZeroU64::new(v.get() as u64).unwrap(), - obj.extract::(py).unwrap() + obj.extract::().unwrap() ); - assert!(obj.extract::(py).is_err()); + assert!(obj.extract::().is_err()); }); } @@ -961,10 +971,10 @@ mod tests { fn test_nonzero_i64_min() { Python::with_gil(|py| { let v = NonZeroI64::new(i64::MIN).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); + assert!(obj.extract::().is_err()); }); } @@ -972,9 +982,9 @@ mod tests { fn test_nonzero_u64_max() { Python::with_gil(|py| { let v = NonZeroU64::new(u64::MAX).unwrap(); - let obj = v.to_object(py); - assert_eq!(v, obj.extract::(py).unwrap()); - assert!(obj.extract::(py).is_err()); + let obj = v.into_pyobject(py).unwrap(); + assert_eq!(v, obj.extract::().unwrap()); + assert!(obj.extract::().is_err()); }); } @@ -982,15 +992,16 @@ mod tests { ($test_mod_name:ident, $t:ty) => ( mod $test_mod_name { use crate::exceptions; - use crate::ToPyObject; + use crate::conversion::IntoPyObject; + use crate::types::PyAnyMethods; use crate::Python; use std::num::*; #[test] fn from_py_string_type_error() { Python::with_gil(|py| { - let obj = ("123").to_object(py); - let err = obj.extract::<$t>(py).unwrap_err(); + let obj = ("123").into_pyobject(py).unwrap(); + let err = obj.extract::<$t>().unwrap_err(); assert!(err.is_instance_of::(py)); }); } @@ -998,8 +1009,8 @@ mod tests { #[test] fn from_py_float_type_error() { Python::with_gil(|py| { - let obj = (12.3).to_object(py); - let err = obj.extract::<$t>(py).unwrap_err(); + let obj = (12.3f64).into_pyobject(py).unwrap(); + let err = obj.extract::<$t>().unwrap_err(); assert!(err.is_instance_of::(py));}); } @@ -1007,8 +1018,8 @@ mod tests { fn to_py_object_and_back() { Python::with_gil(|py| { let val = <$t>::new(123).unwrap(); - let obj = val.to_object(py); - assert_eq!(obj.extract::<$t>(py).unwrap(), val);}); + let obj = val.into_pyobject(py).unwrap(); + assert_eq!(obj.extract::<$t>().unwrap(), val);}); } } ) @@ -1030,22 +1041,22 @@ mod tests { #[test] fn test_i64_bool() { Python::with_gil(|py| { - let obj = true.to_object(py); - assert_eq!(1, obj.extract::(py).unwrap()); - let obj = false.to_object(py); - assert_eq!(0, obj.extract::(py).unwrap()); + let obj = true.into_pyobject(py).unwrap(); + assert_eq!(1, obj.extract::().unwrap()); + let obj = false.into_pyobject(py).unwrap(); + assert_eq!(0, obj.extract::().unwrap()); }) } #[test] fn test_i64_f64() { Python::with_gil(|py| { - let obj = 12.34f64.to_object(py); - let err = obj.extract::(py).unwrap_err(); + let obj = 12.34f64.into_pyobject(py).unwrap(); + let err = obj.extract::().unwrap_err(); assert!(err.is_instance_of::(py)); // with no remainder - let obj = 12f64.to_object(py); - let err = obj.extract::(py).unwrap_err(); + let obj = 12f64.into_pyobject(py).unwrap(); + let err = obj.extract::().unwrap_err(); assert!(err.is_instance_of::(py)); }) } diff --git a/src/conversions/std/option.rs b/src/conversions/std/option.rs index 38eaebd499b..a9c8908faa7 100644 --- a/src/conversions/std/option.rs +++ b/src/conversions/std/option.rs @@ -1,13 +1,14 @@ use crate::{ conversion::IntoPyObject, ffi, types::any::PyAnyMethods, AsPyPointer, Bound, BoundObject, - FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, ToPyObject, + FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, }; /// `Option::Some` is converted like `T`. /// `Option::None` is converted to Python `None`. -impl ToPyObject for Option +#[allow(deprecated)] +impl crate::ToPyObject for Option where - T: ToPyObject, + T: crate::ToPyObject, { fn to_object(&self, py: Python<'_>) -> PyObject { self.as_ref() diff --git a/src/conversions/std/osstr.rs b/src/conversions/std/osstr.rs index 4f956c64ce8..26e3f5d173e 100644 --- a/src/conversions/std/osstr.rs +++ b/src/conversions/std/osstr.rs @@ -3,11 +3,14 @@ use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Bound; use crate::types::any::PyAnyMethods; use crate::types::PyString; -use crate::{ffi, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, ToPyObject}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{ffi, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python}; use std::borrow::Cow; use std::convert::Infallible; use std::ffi::{OsStr, OsString}; +#[allow(deprecated)] impl ToPyObject for OsStr { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -138,6 +141,7 @@ impl IntoPy for &'_ OsStr { } } +#[allow(deprecated)] impl ToPyObject for Cow<'_, OsStr> { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -174,6 +178,7 @@ impl<'py> IntoPyObject<'py> for &Cow<'_, OsStr> { } } +#[allow(deprecated)] impl ToPyObject for OsString { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { diff --git a/src/conversions/std/path.rs b/src/conversions/std/path.rs index f012cc81a27..b651c8d9c87 100644 --- a/src/conversions/std/path.rs +++ b/src/conversions/std/path.rs @@ -3,12 +3,15 @@ use crate::ffi_ptr_ext::FfiPtrExt; use crate::instance::Bound; use crate::types::any::PyAnyMethods; use crate::types::PyString; -use crate::{ffi, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, ToPyObject}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{ffi, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python}; use std::borrow::Cow; use std::convert::Infallible; use std::ffi::OsString; use std::path::{Path, PathBuf}; +#[allow(deprecated)] impl ToPyObject for Path { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -55,6 +58,7 @@ impl<'py> IntoPyObject<'py> for &&Path { } } +#[allow(deprecated)] impl<'a> ToPyObject for Cow<'a, Path> { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -91,6 +95,7 @@ impl<'py> IntoPyObject<'py> for &Cow<'_, Path> { } } +#[allow(deprecated)] impl ToPyObject for PathBuf { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { diff --git a/src/conversions/std/set.rs b/src/conversions/std/set.rs index cc706c43f01..b290423fe49 100644 --- a/src/conversions/std/set.rs +++ b/src/conversions/std/set.rs @@ -2,6 +2,8 @@ use std::{cmp, collections, hash}; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, instance::Bound, @@ -11,9 +13,10 @@ use crate::{ set::{new_from_iter, try_new_from_iter, PySetMethods}, PyFrozenSet, PySet, }, - FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, + FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, }; +#[allow(deprecated)] impl ToPyObject for collections::HashSet where T: hash::Hash + Eq + ToPyObject, @@ -26,6 +29,7 @@ where } } +#[allow(deprecated)] impl ToPyObject for collections::BTreeSet where T: hash::Hash + Eq + ToPyObject, @@ -173,8 +177,9 @@ where #[cfg(test)] mod tests { + use crate::prelude::IntoPyObject; use crate::types::{any::PyAnyMethods, PyFrozenSet, PySet}; - use crate::{IntoPy, PyObject, Python, ToPyObject}; + use crate::{IntoPy, PyObject, Python}; use std::collections::{BTreeSet, HashSet}; #[test] @@ -218,16 +223,16 @@ mod tests { } #[test] - fn test_set_to_object() { + fn test_set_into_pyobject() { Python::with_gil(|py| { let bt: BTreeSet = [1, 2, 3, 4, 5].iter().cloned().collect(); let hs: HashSet = [1, 2, 3, 4, 5].iter().cloned().collect(); - let bto: PyObject = bt.to_object(py); - let hso: PyObject = hs.to_object(py); + let bto = (&bt).into_pyobject(py).unwrap(); + let hso = (&hs).into_pyobject(py).unwrap(); - assert_eq!(bt, bto.extract(py).unwrap()); - assert_eq!(hs, hso.extract(py).unwrap()); + assert_eq!(bt, bto.extract().unwrap()); + assert_eq!(hs, hso.extract().unwrap()); }); } } diff --git a/src/conversions/std/slice.rs b/src/conversions/std/slice.rs index a90d70a49f7..ac70ff4c6c6 100644 --- a/src/conversions/std/slice.rs +++ b/src/conversions/std/slice.rs @@ -2,10 +2,12 @@ use std::borrow::Cow; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, types::{PyByteArray, PyByteArrayMethods, PyBytes}, - Bound, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, + Bound, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, Python, }; impl<'a> IntoPy for &'a [u8] { @@ -69,6 +71,7 @@ impl<'a> crate::conversion::FromPyObjectBound<'a, '_> for Cow<'a, [u8]> { } } +#[allow(deprecated)] impl ToPyObject for Cow<'_, [u8]> { fn to_object(&self, py: Python<'_>) -> Py { PyBytes::new(py, self.as_ref()).into() @@ -77,7 +80,7 @@ impl ToPyObject for Cow<'_, [u8]> { impl IntoPy> for Cow<'_, [u8]> { fn into_py(self, py: Python<'_>) -> Py { - self.to_object(py) + self.into_pyobject(py).unwrap().into_any().unbind() } } @@ -108,7 +111,7 @@ mod tests { conversion::IntoPyObject, ffi, types::{any::PyAnyMethods, PyBytes, PyBytesMethods, PyList}, - Python, ToPyObject, + Python, }; #[test] @@ -138,11 +141,13 @@ mod tests { .extract::>() .unwrap_err(); - let cow = Cow::<[u8]>::Borrowed(b"foobar").to_object(py); - assert!(cow.bind(py).is_instance_of::()); + let cow = Cow::<[u8]>::Borrowed(b"foobar").into_pyobject(py).unwrap(); + assert!(cow.is_instance_of::()); - let cow = Cow::<[u8]>::Owned(b"foobar".to_vec()).to_object(py); - assert!(cow.bind(py).is_instance_of::()); + let cow = Cow::<[u8]>::Owned(b"foobar".to_vec()) + .into_pyobject(py) + .unwrap(); + assert!(cow.is_instance_of::()); }); } diff --git a/src/conversions/std/string.rs b/src/conversions/std/string.rs index 02688641e78..2852ef065ef 100644 --- a/src/conversions/std/string.rs +++ b/src/conversions/std/string.rs @@ -2,15 +2,18 @@ use std::{borrow::Cow, convert::Infallible}; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, instance::Bound, types::{any::PyAnyMethods, string::PyStringMethods, PyString}, - FromPyObject, IntoPy, Py, PyAny, PyObject, PyResult, Python, ToPyObject, + FromPyObject, IntoPy, Py, PyAny, PyObject, PyResult, Python, }; /// Converts a Rust `str` to a Python object. /// See `PyString::new` for details on the conversion. +#[allow(deprecated)] impl ToPyObject for str { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -66,6 +69,7 @@ impl<'py> IntoPyObject<'py> for &&str { /// Converts a Rust `Cow<'_, str>` to a Python object. /// See `PyString::new` for details on the conversion. +#[allow(deprecated)] impl ToPyObject for Cow<'_, str> { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -109,6 +113,7 @@ impl<'py> IntoPyObject<'py> for &Cow<'_, str> { /// Converts a Rust `String` to a Python object. /// See `PyString::new` for details on the conversion. +#[allow(deprecated)] impl ToPyObject for String { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -116,6 +121,7 @@ impl ToPyObject for String { } } +#[allow(deprecated)] impl ToPyObject for char { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -259,9 +265,10 @@ impl FromPyObject<'_> for char { #[cfg(test)] mod tests { + use crate::prelude::IntoPyObject; use crate::types::any::PyAnyMethods; use crate::Python; - use crate::{IntoPy, PyObject, ToPyObject}; + use crate::{IntoPy, PyObject}; use std::borrow::Cow; #[test] @@ -276,13 +283,13 @@ mod tests { } #[test] - fn test_cow_to_object() { + fn test_cow_into_pyobject() { Python::with_gil(|py| { let s = "Hello Python"; - let py_string = Cow::Borrowed(s).to_object(py); - assert_eq!(s, py_string.extract::>(py).unwrap()); - let py_string = Cow::::Owned(s.into()).to_object(py); - assert_eq!(s, py_string.extract::>(py).unwrap()); + let py_string = Cow::Borrowed(s).into_pyobject(py).unwrap(); + assert_eq!(s, py_string.extract::>().unwrap()); + let py_string = Cow::::Owned(s.into()).into_pyobject(py).unwrap(); + assert_eq!(s, py_string.extract::>().unwrap()); }) } @@ -290,8 +297,8 @@ mod tests { fn test_non_bmp() { Python::with_gil(|py| { let s = "\u{1F30F}"; - let py_string = s.to_object(py); - assert_eq!(s, py_string.extract::(py).unwrap()); + let py_string = s.into_pyobject(py).unwrap(); + assert_eq!(s, py_string.extract::().unwrap()); }) } @@ -299,9 +306,9 @@ mod tests { fn test_extract_str() { Python::with_gil(|py| { let s = "Hello Python"; - let py_string = s.to_object(py); + let py_string = s.into_pyobject(py).unwrap(); - let s2: Cow<'_, str> = py_string.bind(py).extract().unwrap(); + let s2: Cow<'_, str> = py_string.extract().unwrap(); assert_eq!(s, s2); }) } @@ -310,8 +317,8 @@ mod tests { fn test_extract_char() { Python::with_gil(|py| { let ch = '😃'; - let py_string = ch.to_object(py); - let ch2: char = py_string.bind(py).extract().unwrap(); + let py_string = ch.into_pyobject(py).unwrap(); + let ch2: char = py_string.extract().unwrap(); assert_eq!(ch, ch2); }) } @@ -320,8 +327,8 @@ mod tests { fn test_extract_char_err() { Python::with_gil(|py| { let s = "Hello Python"; - let py_string = s.to_object(py); - let err: crate::PyResult = py_string.bind(py).extract(); + let py_string = s.into_pyobject(py).unwrap(); + let err: crate::PyResult = py_string.extract(); assert!(err .unwrap_err() .to_string() diff --git a/src/conversions/std/time.rs b/src/conversions/std/time.rs index f8345b12e61..c55a22666de 100755 --- a/src/conversions/std/time.rs +++ b/src/conversions/std/time.rs @@ -8,9 +8,9 @@ use crate::types::PyType; use crate::types::{timezone_utc, PyDateTime, PyDelta, PyDeltaAccess}; #[cfg(Py_LIMITED_API)] use crate::Py; -use crate::{ - intern, Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python, ToPyObject, -}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{intern, Bound, FromPyObject, IntoPy, PyAny, PyErr, PyObject, PyResult, Python}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; const SECONDS_PER_DAY: u64 = 24 * 60 * 60; @@ -52,6 +52,7 @@ impl FromPyObject<'_> for Duration { } } +#[allow(deprecated)] impl ToPyObject for Duration { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -132,6 +133,7 @@ impl FromPyObject<'_> for SystemTime { } } +#[allow(deprecated)] impl ToPyObject for SystemTime { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -249,47 +251,59 @@ mod tests { } #[test] - fn test_duration_topyobject() { + fn test_duration_into_pyobject() { Python::with_gil(|py| { - let assert_eq = |l: PyObject, r: Bound<'_, PyAny>| { - assert!(l.bind(py).eq(r).unwrap()); + let assert_eq = |l: Bound<'_, PyAny>, r: Bound<'_, PyAny>| { + assert!(l.eq(r).unwrap()); }; assert_eq( - Duration::new(0, 0).to_object(py), + Duration::new(0, 0).into_pyobject(py).unwrap().into_any(), new_timedelta(py, 0, 0, 0), ); assert_eq( - Duration::new(86400, 0).to_object(py), + Duration::new(86400, 0) + .into_pyobject(py) + .unwrap() + .into_any(), new_timedelta(py, 1, 0, 0), ); assert_eq( - Duration::new(1, 0).to_object(py), + Duration::new(1, 0).into_pyobject(py).unwrap().into_any(), new_timedelta(py, 0, 1, 0), ); assert_eq( - Duration::new(0, 1_000).to_object(py), + Duration::new(0, 1_000) + .into_pyobject(py) + .unwrap() + .into_any(), new_timedelta(py, 0, 0, 1), ); assert_eq( - Duration::new(0, 1).to_object(py), + Duration::new(0, 1).into_pyobject(py).unwrap().into_any(), new_timedelta(py, 0, 0, 0), ); assert_eq( - Duration::new(86401, 1_000).to_object(py), + Duration::new(86401, 1_000) + .into_pyobject(py) + .unwrap() + .into_any(), new_timedelta(py, 1, 1, 1), ); assert_eq( - Duration::new(86399999999999, 999999000).to_object(py), + Duration::new(86399999999999, 999999000) + .into_pyobject(py) + .unwrap() + .into_any(), timedelta_class(py).getattr("max").unwrap(), ); }); } #[test] - fn test_duration_topyobject_overflow() { + fn test_duration_into_pyobject_overflow() { Python::with_gil(|py| { - assert!(panic::catch_unwind(|| Duration::MAX.to_object(py)).is_err()); + assert!(Duration::MAX.into_pyobject(py).is_err()); }) } diff --git a/src/conversions/std/vec.rs b/src/conversions/std/vec.rs index 1548f604e42..ea3fff117c0 100644 --- a/src/conversions/std/vec.rs +++ b/src/conversions/std/vec.rs @@ -2,8 +2,11 @@ use crate::conversion::IntoPyObject; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; use crate::types::list::new_from_iter; -use crate::{Bound, IntoPy, PyAny, PyErr, PyObject, Python, ToPyObject}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{Bound, IntoPy, PyAny, PyErr, PyObject, Python}; +#[allow(deprecated)] impl ToPyObject for [T] where T: ToPyObject, @@ -15,6 +18,7 @@ where } } +#[allow(deprecated)] impl ToPyObject for Vec where T: ToPyObject, diff --git a/src/err/mod.rs b/src/err/mod.rs index 2ef9e531768..019ee6098dd 100644 --- a/src/err/mod.rs +++ b/src/err/mod.rs @@ -3,11 +3,13 @@ use crate::panic::PanicException; use crate::type_object::PyTypeInfo; use crate::types::any::PyAnyMethods; use crate::types::{string::PyStringMethods, typeobject::PyTypeMethods, PyTraceback, PyType}; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ exceptions::{self, PyBaseException}, ffi, }; -use crate::{Borrowed, IntoPy, Py, PyAny, PyObject, Python, ToPyObject}; +use crate::{Borrowed, BoundObject, IntoPy, Py, PyAny, PyObject, Python}; use std::borrow::Cow; use std::cell::UnsafeCell; use std::ffi::{CStr, CString}; @@ -560,11 +562,11 @@ impl PyErr { /// /// If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass. /// If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match. - pub fn matches(&self, py: Python<'_>, exc: T) -> bool + pub fn matches<'py, T>(&self, py: Python<'py>, exc: T) -> Result where - T: ToPyObject, + T: IntoPyObject<'py>, { - self.is_instance(py, exc.to_object(py).bind(py)) + Ok(self.is_instance(py, &exc.into_pyobject(py)?.into_any().as_borrowed())) } /// Returns true if the current exception is instance of `T`. @@ -884,6 +886,7 @@ impl IntoPy for PyErr { } } +#[allow(deprecated)] impl ToPyObject for PyErr { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -933,7 +936,11 @@ impl PyErrArguments for PyDowncastErrorArguments { Ok(qn) => qn.to_cow().unwrap_or(FAILED_TO_EXTRACT), Err(_) => FAILED_TO_EXTRACT, }; - format!("'{}' object cannot be converted to '{}'", from, self.to).to_object(py) + format!("'{}' object cannot be converted to '{}'", from, self.to) + .into_pyobject(py) + .unwrap() + .into_any() + .unbind() } } @@ -1187,18 +1194,20 @@ mod tests { fn test_pyerr_matches() { Python::with_gil(|py| { let err = PyErr::new::("foo"); - assert!(err.matches(py, PyValueError::type_object(py))); + assert!(err.matches(py, PyValueError::type_object(py)).unwrap()); - assert!(err.matches( - py, - (PyValueError::type_object(py), PyTypeError::type_object(py)) - )); + assert!(err + .matches( + py, + (PyValueError::type_object(py), PyTypeError::type_object(py)) + ) + .unwrap()); - assert!(!err.matches(py, PyTypeError::type_object(py))); + assert!(!err.matches(py, PyTypeError::type_object(py)).unwrap()); // String is not a valid exception class, so we should get a TypeError let err: PyErr = PyErr::from_type(crate::types::PyString::type_object(py), "foo"); - assert!(err.matches(py, PyTypeError::type_object(py))); + assert!(err.matches(py, PyTypeError::type_object(py)).unwrap()); }) } diff --git a/src/impl_/pyclass.rs b/src/impl_/pyclass.rs index bf94503f1c0..4e3ed140a76 100644 --- a/src/impl_/pyclass.rs +++ b/src/impl_/pyclass.rs @@ -1,3 +1,5 @@ +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ conversion::IntoPyObject, exceptions::{PyAttributeError, PyNotImplementedError, PyRuntimeError, PyValueError}, @@ -11,7 +13,6 @@ use crate::{ pyclass_init::PyObjectInit, types::{any::PyAnyMethods, PyBool}, Borrowed, BoundObject, IntoPy, Py, PyAny, PyClass, PyErr, PyRef, PyResult, PyTypeInfo, Python, - ToPyObject, }; use std::{ borrow::Cow, @@ -1292,6 +1293,7 @@ impl< /// Fallback case; Field is not `Py`; try to use `ToPyObject` to avoid potentially expensive /// clones of containers like `Vec` +#[allow(deprecated)] impl< ClassT: PyClass, FieldT: ToPyObject, @@ -1443,6 +1445,7 @@ impl IsPyT> { probe!(IsToPyObject); +#[allow(deprecated)] impl IsToPyObject { pub const VALUE: bool = true; } @@ -1492,6 +1495,7 @@ where unsafe { obj.cast::().add(Offset::offset()).cast::() } } +#[allow(deprecated)] fn pyo3_get_value_topyobject< ClassT: PyClass, FieldT: ToPyObject, diff --git a/src/instance.rs b/src/instance.rs index 1e15624929e..716689c0ae2 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -6,9 +6,11 @@ use crate::pycell::{PyBorrowError, PyBorrowMutError}; use crate::pyclass::boolean_struct::{False, True}; use crate::types::{any::PyAnyMethods, string::PyStringMethods, typeobject::PyTypeMethods}; use crate::types::{DerefToPyAny, PyDict, PyString, PyTuple}; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ ffi, AsPyPointer, DowncastError, FromPyObject, IntoPy, PyAny, PyClass, PyClassInitializer, - PyRef, PyRefMut, PyTypeInfo, Python, ToPyObject, + PyRef, PyRefMut, PyTypeInfo, Python, }; use crate::{gil, PyTypeCheck}; use std::marker::PhantomData; @@ -806,6 +808,7 @@ impl Clone for Borrowed<'_, '_, T> { impl Copy for Borrowed<'_, '_, T> {} +#[allow(deprecated)] impl ToPyObject for Borrowed<'_, '_, T> { /// Converts `Py` instance -> PyObject. #[inline] @@ -1686,6 +1689,7 @@ impl Py { } } +#[allow(deprecated)] impl ToPyObject for Py { /// Converts `Py` instance -> PyObject. #[inline] @@ -1706,10 +1710,11 @@ impl IntoPy for Py { impl IntoPy for &'_ Py { #[inline] fn into_py(self, py: Python<'_>) -> PyObject { - self.to_object(py) + self.into_pyobject(py).unwrap().into_any().unbind() } } +#[allow(deprecated)] impl ToPyObject for Bound<'_, T> { /// Converts `&Bound` instance -> PyObject, increasing the reference count. #[inline] @@ -1730,7 +1735,7 @@ impl IntoPy for &Bound<'_, T> { /// Converts `&Bound` instance -> PyObject, increasing the reference count. #[inline] fn into_py(self, py: Python<'_>) -> PyObject { - self.to_object(py) + self.into_pyobject(py).unwrap().into_any().unbind() } } @@ -1939,30 +1944,30 @@ impl PyObject { #[cfg(test)] mod tests { use super::{Bound, Py, PyObject}; + use crate::prelude::IntoPyObject; use crate::tests::common::generate_unique_module_name; use crate::types::{dict::IntoPyDict, PyAnyMethods, PyCapsule, PyDict, PyString}; - use crate::{ffi, Borrowed, PyAny, PyResult, Python, ToPyObject}; + use crate::{ffi, Borrowed, PyAny, PyResult, Python}; use pyo3_ffi::c_str; use std::ffi::CStr; #[test] fn test_call() { Python::with_gil(|py| { - let obj = py.get_type::().to_object(py); + let obj = py.get_type::().into_pyobject(py).unwrap(); - let assert_repr = |obj: &Bound<'_, PyAny>, expected: &str| { + let assert_repr = |obj: Bound<'_, PyAny>, expected: &str| { assert_eq!(obj.repr().unwrap(), expected); }; - assert_repr(obj.call0(py).unwrap().bind(py), "{}"); - assert_repr(obj.call1(py, ()).unwrap().bind(py), "{}"); - assert_repr(obj.call(py, (), None).unwrap().bind(py), "{}"); + assert_repr(obj.call0().unwrap(), "{}"); + assert_repr(obj.call1(()).unwrap(), "{}"); + assert_repr(obj.call((), None).unwrap(), "{}"); - assert_repr(obj.call1(py, ((('x', 1),),)).unwrap().bind(py), "{'x': 1}"); + assert_repr(obj.call1(((('x', 1),),)).unwrap(), "{'x': 1}"); assert_repr( - obj.call(py, (), Some(&[('x', 1)].into_py_dict(py).unwrap())) - .unwrap() - .bind(py), + obj.call((), Some(&[('x', 1)].into_py_dict(py).unwrap())) + .unwrap(), "{'x': 1}", ); }) @@ -2095,7 +2100,7 @@ a = A() #[test] fn test_debug_fmt() { Python::with_gil(|py| { - let obj = "hello world".to_object(py).into_bound(py); + let obj = "hello world".into_pyobject(py).unwrap(); assert_eq!(format!("{:?}", obj), "'hello world'"); }); } @@ -2103,7 +2108,7 @@ a = A() #[test] fn test_display_fmt() { Python::with_gil(|py| { - let obj = "hello world".to_object(py).into_bound(py); + let obj = "hello world".into_pyobject(py).unwrap(); assert_eq!(format!("{}", obj), "hello world"); }); } diff --git a/src/lib.rs b/src/lib.rs index 8144ef740e0..c1e8cfde16d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -320,7 +320,9 @@ #![doc = concat!("[Features chapter of the guide]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/features.html#features-reference \"Features Reference - PyO3 user guide\"")] //! [`Ungil`]: crate::marker::Ungil pub use crate::class::*; -pub use crate::conversion::{AsPyPointer, FromPyObject, IntoPy, ToPyObject}; +#[allow(deprecated)] +pub use crate::conversion::ToPyObject; +pub use crate::conversion::{AsPyPointer, FromPyObject, IntoPy}; pub use crate::err::{DowncastError, DowncastIntoError, PyErr, PyErrArguments, PyResult, ToPyErr}; #[cfg(not(any(PyPy, GraalPy)))] pub use crate::gil::{prepare_freethreaded_python, with_embedded_python_interpreter}; diff --git a/src/macros.rs b/src/macros.rs index 936dbd43af0..d2fa6f31ada 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -104,8 +104,9 @@ macro_rules! py_run { macro_rules! py_run_impl { ($py:expr, $($val:ident)+, $code:expr) => {{ use $crate::types::IntoPyDict; - use $crate::ToPyObject; - let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict($py).unwrap(); + use $crate::conversion::IntoPyObject; + use $crate::BoundObject; + let d = [$((stringify!($val), (&$val).into_pyobject($py).unwrap().into_any().into_bound()),)+].into_py_dict($py).unwrap(); $crate::py_run_impl!($py, *d, $code) }}; ($py:expr, *$dict:expr, $code:expr) => {{ diff --git a/src/prelude.rs b/src/prelude.rs index b2b86c8449d..97f3e35afa1 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -8,7 +8,9 @@ //! use pyo3::prelude::*; //! ``` -pub use crate::conversion::{FromPyObject, IntoPy, IntoPyObject, ToPyObject}; +#[allow(deprecated)] +pub use crate::conversion::ToPyObject; +pub use crate::conversion::{FromPyObject, IntoPy, IntoPyObject}; pub use crate::err::{PyErr, PyResult}; pub use crate::instance::{Borrowed, Bound, Py, PyObject}; pub use crate::marker::Python; diff --git a/src/tests/common.rs b/src/tests/common.rs index caa4120b720..cd0374e9019 100644 --- a/src/tests/common.rs +++ b/src/tests/common.rs @@ -40,14 +40,15 @@ mod inner { // Case1: idents & no err_msg ($py:expr, $($val:ident)+, $code:expr, $err:ident) => {{ use pyo3::types::IntoPyDict; - let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict($py).unwrap(); + use pyo3::BoundObject; + let d = [$((stringify!($val), (&$val).into_pyobject($py).unwrap().into_any().into_bound()),)+].into_py_dict($py).unwrap(); py_expect_exception!($py, *d, $code, $err) }}; // Case2: dict & no err_msg ($py:expr, *$dict:expr, $code:expr, $err:ident) => {{ let res = $py.run(&std::ffi::CString::new($code).unwrap(), None, Some(&$dict.as_borrowed())); let err = res.expect_err(&format!("Did not raise {}", stringify!($err))); - if !err.matches($py, $py.get_type::()) { + if !err.matches($py, $py.get_type::()).unwrap() { panic!("Expected {} but got {:?}", stringify!($err), err) } err diff --git a/src/types/any.rs b/src/types/any.rs index 409630e12b2..f13d5b90b51 100644 --- a/src/types/any.rs +++ b/src/types/any.rs @@ -1606,11 +1606,13 @@ mod tests { use crate::{ basic::CompareOp, ffi, + prelude::IntoPyObject, tests::common::generate_unique_module_name, types::{IntoPyDict, PyAny, PyAnyMethods, PyBool, PyInt, PyList, PyModule, PyTypeMethods}, - Bound, PyTypeInfo, Python, ToPyObject, + Bound, BoundObject, PyTypeInfo, Python, }; use pyo3_ffi::c_str; + use std::fmt::Debug; #[test] fn test_lookup_special() { @@ -1700,10 +1702,10 @@ class NonHeapNonDescriptorInt: #[test] fn test_call_with_kwargs() { Python::with_gil(|py| { - let list = vec![3, 6, 5, 4, 7].to_object(py); + let list = vec![3, 6, 5, 4, 7].into_pyobject(py).unwrap(); let dict = vec![("reverse", true)].into_py_dict(py).unwrap(); - list.call_method(py, "sort", (), Some(&dict)).unwrap(); - assert_eq!(list.extract::>(py).unwrap(), vec![7, 6, 5, 4, 3]); + list.call_method("sort", (), Some(&dict)).unwrap(); + assert_eq!(list.extract::>().unwrap(), vec![7, 6, 5, 4, 3]); }); } @@ -1766,7 +1768,7 @@ class SimpleClass: #[test] fn test_hasattr() { Python::with_gil(|py| { - let x = 5.to_object(py).into_bound(py); + let x = 5i32.into_pyobject(py).unwrap(); assert!(x.is_instance_of::()); assert!(x.hasattr("to_bytes").unwrap()); @@ -1813,10 +1815,10 @@ class SimpleClass: #[test] fn test_any_is_instance_of() { Python::with_gil(|py| { - let x = 5.to_object(py).into_bound(py); + let x = 5i32.into_pyobject(py).unwrap(); assert!(x.is_instance_of::()); - let l = vec![&x, &x].to_object(py).into_bound(py); + let l = vec![&x, &x].into_pyobject(py).unwrap(); assert!(l.is_instance_of::()); }); } @@ -1824,7 +1826,7 @@ class SimpleClass: #[test] fn test_any_is_instance() { Python::with_gil(|py| { - let l = vec![1u8, 2].to_object(py).into_bound(py); + let l = vec![1i8, 2].into_pyobject(py).unwrap(); assert!(l.is_instance(&py.get_type::()).unwrap()); }); } @@ -1832,7 +1834,7 @@ class SimpleClass: #[test] fn test_any_is_exact_instance_of() { Python::with_gil(|py| { - let x = 5.to_object(py).into_bound(py); + let x = 5i32.into_pyobject(py).unwrap(); assert!(x.is_exact_instance_of::()); let t = PyBool::new(py, true); @@ -1840,7 +1842,7 @@ class SimpleClass: assert!(!t.is_exact_instance_of::()); assert!(t.is_exact_instance_of::()); - let l = vec![&x, &x].to_object(py).into_bound(py); + let l = vec![&x, &x].into_pyobject(py).unwrap(); assert!(l.is_exact_instance_of::()); }); } @@ -1859,34 +1861,36 @@ class SimpleClass: fn test_any_contains() { Python::with_gil(|py| { let v: Vec = vec![1, 1, 2, 3, 5, 8]; - let ob = v.to_object(py).into_bound(py); + let ob = v.into_pyobject(py).unwrap(); - let bad_needle = 7i32.to_object(py); + let bad_needle = 7i32.into_pyobject(py).unwrap(); assert!(!ob.contains(&bad_needle).unwrap()); - let good_needle = 8i32.to_object(py); + let good_needle = 8i32.into_pyobject(py).unwrap(); assert!(ob.contains(&good_needle).unwrap()); - let type_coerced_needle = 8f32.to_object(py); + let type_coerced_needle = 8f32.into_pyobject(py).unwrap(); assert!(ob.contains(&type_coerced_needle).unwrap()); let n: u32 = 42; - let bad_haystack = n.to_object(py).into_bound(py); - let irrelevant_needle = 0i32.to_object(py); + let bad_haystack = n.into_pyobject(py).unwrap(); + let irrelevant_needle = 0i32.into_pyobject(py).unwrap(); assert!(bad_haystack.contains(&irrelevant_needle).is_err()); }); } // This is intentionally not a test, it's a generic function used by the tests below. - fn test_eq_methods_generic(list: &[T]) + fn test_eq_methods_generic<'a, T>(list: &'a [T]) where - T: PartialEq + PartialOrd + ToPyObject, + T: PartialEq + PartialOrd, + for<'py> &'a T: IntoPyObject<'py>, + for<'py> <&'a T as IntoPyObject<'py>>::Error: Debug, { Python::with_gil(|py| { for a in list { for b in list { - let a_py = a.to_object(py).into_bound(py); - let b_py = b.to_object(py).into_bound(py); + let a_py = a.into_pyobject(py).unwrap().into_any().into_bound(); + let b_py = b.into_pyobject(py).unwrap().into_any().into_bound(); assert_eq!( a.lt(b), @@ -1944,13 +1948,13 @@ class SimpleClass: #[test] fn test_eq_methods_integers() { let ints = [-4, -4, 1, 2, 0, -100, 1_000_000]; - test_eq_methods_generic(&ints); + test_eq_methods_generic::(&ints); } #[test] fn test_eq_methods_strings() { let strings = ["Let's", "test", "some", "eq", "methods"]; - test_eq_methods_generic(&strings); + test_eq_methods_generic::<&str>(&strings); } #[test] @@ -1965,20 +1969,20 @@ class SimpleClass: 10.0 / 3.0, -1_000_000.0, ]; - test_eq_methods_generic(&floats); + test_eq_methods_generic::(&floats); } #[test] fn test_eq_methods_bools() { let bools = [true, false]; - test_eq_methods_generic(&bools); + test_eq_methods_generic::(&bools); } #[test] fn test_rich_compare_type_error() { Python::with_gil(|py| { - let py_int = 1.to_object(py).into_bound(py); - let py_str = "1".to_object(py).into_bound(py); + let py_int = 1i32.into_pyobject(py).unwrap(); + let py_str = "1".into_pyobject(py).unwrap(); assert!(py_int.rich_compare(&py_str, CompareOp::Lt).is_err()); assert!(!py_int @@ -2000,7 +2004,7 @@ class SimpleClass: assert!(v.is_ellipsis()); - let not_ellipsis = 5.to_object(py).into_bound(py); + let not_ellipsis = 5i32.into_pyobject(py).unwrap(); assert!(!not_ellipsis.is_ellipsis()); }); } @@ -2010,7 +2014,7 @@ class SimpleClass: Python::with_gil(|py| { assert!(PyList::type_object(py).is_callable()); - let not_callable = 5.to_object(py).into_bound(py); + let not_callable = 5i32.into_pyobject(py).unwrap(); assert!(!not_callable.is_callable()); }); } @@ -2024,7 +2028,7 @@ class SimpleClass: let list = PyList::new(py, vec![1, 2, 3]).unwrap().into_any(); assert!(!list.is_empty().unwrap()); - let not_container = 5.to_object(py).into_bound(py); + let not_container = 5i32.into_pyobject(py).unwrap(); assert!(not_container.is_empty().is_err()); }); } diff --git a/src/types/boolobject.rs b/src/types/boolobject.rs index 8f211a27a54..526f68044a4 100644 --- a/src/types/boolobject.rs +++ b/src/types/boolobject.rs @@ -1,9 +1,11 @@ #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ exceptions::PyTypeError, ffi, ffi_ptr_ext::FfiPtrExt, instance::Bound, types::typeobject::PyTypeMethods, Borrowed, FromPyObject, IntoPy, PyAny, PyObject, PyResult, - Python, ToPyObject, + Python, }; use super::any::PyAnyMethods; @@ -145,6 +147,7 @@ impl PartialEq> for &'_ bool { } /// Converts a Rust `bool` to a Python `bool`. +#[allow(deprecated)] impl ToPyObject for bool { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -251,11 +254,11 @@ impl FromPyObject<'_> for bool { #[cfg(test)] mod tests { + use crate::prelude::IntoPyObject; use crate::types::any::PyAnyMethods; use crate::types::boolobject::PyBoolMethods; use crate::types::PyBool; use crate::Python; - use crate::ToPyObject; #[test] fn test_true() { @@ -263,7 +266,7 @@ mod tests { assert!(PyBool::new(py, true).is_true()); let t = PyBool::new(py, true); assert!(t.extract::().unwrap()); - assert!(true.to_object(py).is(&*PyBool::new(py, true))); + assert!(true.into_pyobject(py).unwrap().is(&*PyBool::new(py, true))); }); } @@ -273,7 +276,10 @@ mod tests { assert!(!PyBool::new(py, false).is_true()); let t = PyBool::new(py, false); assert!(!t.extract::().unwrap()); - assert!(false.to_object(py).is(&*PyBool::new(py, false))); + assert!(false + .into_pyobject(py) + .unwrap() + .is(&*PyBool::new(py, false))); }); } diff --git a/src/types/dict.rs b/src/types/dict.rs index c4de7bae46a..3623c44c771 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -624,7 +624,6 @@ where mod tests { use super::*; use crate::types::PyTuple; - use crate::ToPyObject; use std::collections::{BTreeMap, HashMap}; #[test] @@ -709,13 +708,11 @@ mod tests { #[test] fn test_len() { Python::with_gil(|py| { - let mut v = HashMap::new(); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let mut v = HashMap::::new(); + let dict = (&v).into_pyobject(py).unwrap(); assert_eq!(0, dict.len()); v.insert(7, 32); - let ob = v.to_object(py); - let dict2 = ob.downcast_bound::(py).unwrap(); + let dict2 = v.into_pyobject(py).unwrap(); assert_eq!(1, dict2.len()); }); } @@ -725,8 +722,7 @@ mod tests { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); assert!(dict.contains(7i32).unwrap()); assert!(!dict.contains(8i32).unwrap()); }); @@ -737,8 +733,7 @@ mod tests { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); assert_eq!( 32, dict.get_item(7i32) @@ -792,8 +787,7 @@ mod tests { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!( @@ -835,8 +829,7 @@ mod tests { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = (&v).into_pyobject(py).unwrap(); assert!(dict.set_item(7i32, 42i32).is_ok()); // change assert!(dict.set_item(8i32, 123i32).is_ok()); // insert assert_eq!(32i32, v[&7i32]); // not updated! @@ -849,8 +842,7 @@ mod tests { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); assert!(dict.del_item(7i32).is_ok()); assert_eq!(0, dict.len()); assert!(dict.get_item(7i32).unwrap().is_none()); @@ -862,8 +854,7 @@ mod tests { Python::with_gil(|py| { let mut v = HashMap::new(); v.insert(7, 32); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = (&v).into_pyobject(py).unwrap(); assert!(dict.del_item(7i32).is_ok()); // change assert_eq!(32i32, *v.get(&7i32).unwrap()); // not updated! }); @@ -876,8 +867,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; let mut value_sum = 0; @@ -898,8 +888,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut key_sum = 0; for el in dict.keys() { @@ -916,8 +905,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); // Can't just compare against a vector of tuples since we don't have a guaranteed ordering. let mut values_sum = 0; for el in dict.values() { @@ -934,8 +922,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { @@ -954,8 +941,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict: &Bound<'_, PyDict> = ob.downcast_bound(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { @@ -975,10 +961,9 @@ mod tests { v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = (&v).into_pyobject(py).unwrap(); - for (key, value) in dict { + for (key, value) in &dict { dict.set_item(key, value.extract::().unwrap() + 7) .unwrap(); } @@ -993,8 +978,7 @@ mod tests { for i in 0..10 { v.insert(i * 2, i * 2); } - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); for (i, (key, value)) in dict.iter().enumerate() { let key = key.extract::().unwrap(); @@ -1018,8 +1002,7 @@ mod tests { for i in 0..10 { v.insert(i * 2, i * 2); } - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); for (i, (key, value)) in dict.iter().enumerate() { let key = key.extract::().unwrap(); @@ -1042,8 +1025,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = (&v).into_pyobject(py).unwrap(); let mut iter = dict.iter(); assert_eq!(iter.size_hint(), (v.len(), Some(v.len()))); @@ -1068,8 +1050,7 @@ mod tests { v.insert(7, 32); v.insert(8, 42); v.insert(9, 123); - let ob = v.to_object(py); - let dict = ob.downcast_bound::(py).unwrap(); + let dict = v.into_pyobject(py).unwrap(); let mut key_sum = 0; let mut value_sum = 0; for (key, value) in dict { diff --git a/src/types/float.rs b/src/types/float.rs index 58fdba609af..f9bf673ac98 100644 --- a/src/types/float.rs +++ b/src/types/float.rs @@ -2,9 +2,11 @@ use super::any::PyAnyMethods; use crate::conversion::IntoPyObject; #[cfg(feature = "experimental-inspect")] use crate::inspect::types::TypeInfo; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ ffi, ffi_ptr_ext::FfiPtrExt, instance::Bound, Borrowed, FromPyObject, IntoPy, PyAny, PyErr, - PyObject, PyResult, Python, ToPyObject, + PyObject, PyResult, Python, }; use std::convert::Infallible; use std::os::raw::c_double; @@ -76,6 +78,7 @@ impl<'py> PyFloatMethods<'py> for Bound<'py, PyFloat> { } } +#[allow(deprecated)] impl ToPyObject for f64 { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -147,6 +150,7 @@ impl<'py> FromPyObject<'py> for f64 { } } +#[allow(deprecated)] impl ToPyObject for f32 { #[inline] fn to_object(&self, py: Python<'_>) -> PyObject { @@ -279,8 +283,9 @@ impl_partial_eq_for_float!(f32); #[cfg(test)] mod tests { use crate::{ - types::{PyFloat, PyFloatMethods}, - Python, ToPyObject, + conversion::IntoPyObject, + types::{PyAnyMethods, PyFloat, PyFloatMethods}, + Python, }; macro_rules! num_to_py_object_and_back ( @@ -292,8 +297,8 @@ mod tests { Python::with_gil(|py| { let val = 123 as $t1; - let obj = val.to_object(py); - assert_approx_eq!(obj.extract::<$t2>(py).unwrap(), val as $t2); + let obj = val.into_pyobject(py).unwrap(); + assert_approx_eq!(obj.extract::<$t2>().unwrap(), val as $t2); }); } ) diff --git a/src/types/frozenset.rs b/src/types/frozenset.rs index 88d726b136d..acf4386e785 100644 --- a/src/types/frozenset.rs +++ b/src/types/frozenset.rs @@ -6,7 +6,7 @@ use crate::{ ffi_ptr_ext::FfiPtrExt, py_result_ext::PyResultExt, types::any::PyAnyMethods, - Bound, PyAny, Python, ToPyObject, + Bound, PyAny, Python, }; use crate::{Borrowed, BoundObject}; use std::ptr; @@ -103,8 +103,9 @@ impl PyFrozenSet { /// Deprecated name for [`PyFrozenSet::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyFrozenSet::new`")] + #[allow(deprecated)] #[inline] - pub fn new_bound<'a, 'p, T: ToPyObject + 'a>( + pub fn new_bound<'a, 'p, T: crate::ToPyObject + 'a>( py: Python<'p>, elements: impl IntoIterator, ) -> PyResult> { diff --git a/src/types/iterator.rs b/src/types/iterator.rs index 788ed79c475..80703830d53 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -107,14 +107,14 @@ impl PyTypeCheck for PyIterator { mod tests { use super::PyIterator; use crate::exceptions::PyTypeError; + use crate::prelude::IntoPyObject; use crate::types::{PyAnyMethods, PyDict, PyList, PyListMethods}; - use crate::{ffi, Python, ToPyObject}; + use crate::{ffi, Python}; #[test] fn vec_iter() { Python::with_gil(|py| { - let obj = vec![10, 20].to_object(py); - let inst = obj.bind(py); + let inst = vec![10, 20].into_pyobject(py).unwrap(); let mut it = inst.iter().unwrap(); assert_eq!( 10_i32, @@ -131,9 +131,9 @@ mod tests { #[test] fn iter_refcnt() { let (obj, count) = Python::with_gil(|py| { - let obj = vec![10, 20].to_object(py); - let count = obj.get_refcnt(py); - (obj, count) + let obj = vec![10, 20].into_pyobject(py).unwrap(); + let count = obj.get_refcnt(); + (obj.unbind(), count) }); Python::with_gil(|py| { @@ -161,18 +161,14 @@ mod tests { list.append(10).unwrap(); list.append(&obj).unwrap(); count = obj.get_refcnt(); - list.to_object(py) + list }; { - let inst = list.bind(py); - let mut it = inst.iter().unwrap(); - - assert_eq!( - 10_i32, - it.next().unwrap().unwrap().extract::<'_, i32>().unwrap() - ); - assert!(it.next().unwrap().unwrap().is(&obj)); + let mut it = list.iter(); + + assert_eq!(10_i32, it.next().unwrap().extract::<'_, i32>().unwrap()); + assert!(it.next().unwrap().is(&obj)); assert!(it.next().is_none()); } assert_eq!(count, obj.get_refcnt()); @@ -243,8 +239,8 @@ def fibonacci(target): #[test] fn int_not_iterable() { Python::with_gil(|py| { - let x = 5.to_object(py); - let err = PyIterator::from_object(x.bind(py)).unwrap_err(); + let x = 5i32.into_pyobject(py).unwrap(); + let err = PyIterator::from_object(&x).unwrap_err(); assert!(err.is_instance_of::(py)); }); diff --git a/src/types/list.rs b/src/types/list.rs index a8952273341..dc236c12a4a 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -5,7 +5,7 @@ use crate::ffi::{self, Py_ssize_t}; use crate::ffi_ptr_ext::FfiPtrExt; use crate::internal_tricks::get_ssize_index; use crate::types::{PySequence, PyTuple}; -use crate::{Borrowed, Bound, BoundObject, PyAny, PyObject, Python, ToPyObject}; +use crate::{Borrowed, Bound, BoundObject, PyAny, PyObject, Python}; use crate::prelude::IntoPyObject; use crate::types::any::PyAnyMethods; @@ -116,6 +116,7 @@ impl PyList { /// Deprecated name for [`PyList::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyList::new`")] + #[allow(deprecated)] #[inline] #[track_caller] pub fn new_bound( @@ -123,7 +124,7 @@ impl PyList { elements: impl IntoIterator, ) -> Bound<'_, PyList> where - T: ToPyObject, + T: crate::ToPyObject, U: ExactSizeIterator, { Self::new(py, elements.into_iter().map(|e| e.to_object(py))).unwrap() diff --git a/src/types/none.rs b/src/types/none.rs index 47a1ac25848..9a0c9b11f45 100644 --- a/src/types/none.rs +++ b/src/types/none.rs @@ -1,7 +1,8 @@ use crate::ffi_ptr_ext::FfiPtrExt; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ ffi, types::any::PyAnyMethods, Borrowed, Bound, IntoPy, PyAny, PyObject, PyTypeInfo, Python, - ToPyObject, }; /// Represents the Python `None` object. @@ -50,6 +51,7 @@ unsafe impl PyTypeInfo for PyNone { } /// `()` is converted to Python `None`. +#[allow(deprecated)] impl ToPyObject for () { fn to_object(&self, py: Python<'_>) -> PyObject { PyNone::get(py).into_py(py) @@ -67,7 +69,7 @@ impl IntoPy for () { mod tests { use crate::types::any::PyAnyMethods; use crate::types::{PyDict, PyNone}; - use crate::{IntoPy, PyObject, PyTypeInfo, Python, ToPyObject}; + use crate::{IntoPy, PyObject, PyTypeInfo, Python}; #[test] fn test_none_is_itself() { Python::with_gil(|py| { @@ -91,7 +93,9 @@ mod tests { } #[test] + #[allow(deprecated)] fn test_unit_to_object_is_none() { + use crate::ToPyObject; Python::with_gil(|py| { assert!(().to_object(py).downcast_bound::(py).is_ok()); }) diff --git a/src/types/set.rs b/src/types/set.rs index eddc2eb8885..229c9035898 100644 --- a/src/types/set.rs +++ b/src/types/set.rs @@ -1,5 +1,7 @@ use crate::conversion::IntoPyObject; use crate::types::PyIterator; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ err::{self, PyErr, PyResult}, ffi_ptr_ext::FfiPtrExt, @@ -7,7 +9,7 @@ use crate::{ py_result_ext::PyResultExt, types::any::PyAnyMethods, }; -use crate::{ffi, Borrowed, BoundObject, PyAny, Python, ToPyObject}; +use crate::{ffi, Borrowed, BoundObject, PyAny, Python}; use std::ptr; /// Represents a Python `set`. @@ -55,6 +57,7 @@ impl PySet { /// Deprecated name for [`PySet::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PySet::new`")] + #[allow(deprecated)] #[inline] pub fn new_bound<'a, 'p, T: ToPyObject + 'a>( py: Python<'p>, @@ -285,6 +288,7 @@ impl<'py> ExactSizeIterator for BoundSetIterator<'py> { } } +#[allow(deprecated)] #[inline] pub(crate) fn new_from_iter( py: Python<'_>, diff --git a/src/types/slice.rs b/src/types/slice.rs index 528e7893476..5ac59c33e68 100644 --- a/src/types/slice.rs +++ b/src/types/slice.rs @@ -3,7 +3,9 @@ use crate::ffi; use crate::ffi_ptr_ext::FfiPtrExt; use crate::prelude::IntoPyObject; use crate::types::any::PyAnyMethods; -use crate::{Bound, PyAny, PyObject, Python, ToPyObject}; +#[allow(deprecated)] +use crate::ToPyObject; +use crate::{Bound, PyAny, PyObject, Python}; use std::convert::Infallible; /// Represents a Python `slice`. @@ -135,6 +137,7 @@ impl<'py> PySliceMethods<'py> for Bound<'py, PySlice> { } } +#[allow(deprecated)] impl ToPyObject for PySliceIndices { fn to_object(&self, py: Python<'_>) -> PyObject { PySlice::new(py, self.start, self.stop, self.step).into() diff --git a/src/types/string.rs b/src/types/string.rs index c4aea67423d..76c3eda03f2 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -577,7 +577,8 @@ impl PartialEq> for &'_ str { #[cfg(test)] mod tests { use super::*; - use crate::{PyObject, ToPyObject}; + use crate::prelude::IntoPyObject; + use crate::PyObject; #[test] fn test_to_cow_utf8() { @@ -650,8 +651,7 @@ mod tests { #[test] fn test_debug_string() { Python::with_gil(|py| { - let v = "Hello\n".to_object(py); - let s = v.downcast_bound::(py).unwrap(); + let s = "Hello\n".into_pyobject(py).unwrap(); assert_eq!(format!("{:?}", s), "'Hello\\n'"); }) } @@ -659,8 +659,7 @@ mod tests { #[test] fn test_display_string() { Python::with_gil(|py| { - let v = "Hello\n".to_object(py); - let s = v.downcast_bound::(py).unwrap(); + let s = "Hello\n".into_pyobject(py).unwrap(); assert_eq!(format!("{}", s), "Hello\n"); }) } diff --git a/src/types/tuple.rs b/src/types/tuple.rs index 8f26e4d89e6..ffa2e5f582e 100644 --- a/src/types/tuple.rs +++ b/src/types/tuple.rs @@ -10,9 +10,11 @@ use crate::internal_tricks::get_ssize_index; use crate::types::{ any::PyAnyMethods, sequence::PySequenceMethods, PyDict, PyList, PySequence, PyString, }; +#[allow(deprecated)] +use crate::ToPyObject; use crate::{ exceptions, Bound, BoundObject, FromPyObject, IntoPy, Py, PyAny, PyErr, PyObject, PyResult, - Python, ToPyObject, + Python, }; #[inline] @@ -111,6 +113,7 @@ impl PyTuple { /// Deprecated name for [`PyTuple::new`]. #[deprecated(since = "0.23.0", note = "renamed to `PyTuple::new`")] + #[allow(deprecated)] #[track_caller] #[inline] pub fn new_bound( @@ -169,14 +172,13 @@ pub trait PyTupleMethods<'py>: crate::sealed::Sealed { /// Gets the tuple item at the specified index. /// # Example /// ``` - /// use pyo3::{prelude::*, types::PyTuple}; + /// use pyo3::prelude::*; /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { - /// let ob = (1, 2, 3).to_object(py); - /// let tuple = ob.downcast_bound::(py).unwrap(); + /// let tuple = (1, 2, 3).into_pyobject(py)?; /// let obj = tuple.get_item(0); - /// assert_eq!(obj.unwrap().extract::().unwrap(), 1); + /// assert_eq!(obj?.extract::()?, 1); /// Ok(()) /// }) /// # } @@ -519,6 +521,7 @@ fn wrong_tuple_length(t: &Bound<'_, PyTuple>, expected_length: usize) -> PyErr { } macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => { + #[allow(deprecated)] impl <$($T: ToPyObject),+> ToPyObject for ($($T,)+) { fn to_object(&self, py: Python<'_>) -> PyObject { array_into_tuple(py, [$(self.$n.to_object(py)),+]).into() diff --git a/src/types/weakref/proxy.rs b/src/types/weakref/proxy.rs index 798b4b435c7..56f1b9000ee 100644 --- a/src/types/weakref/proxy.rs +++ b/src/types/weakref/proxy.rs @@ -1,9 +1,10 @@ use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; +use crate::prelude::IntoPyObject; use crate::py_result_ext::PyResultExt; use crate::type_object::PyTypeCheck; use crate::types::{any::PyAny, PyNone}; -use crate::{ffi, Bound, ToPyObject}; +use crate::{ffi, Bound, BoundObject}; use super::PyWeakrefMethods; @@ -148,7 +149,7 @@ impl PyWeakrefProxy { callback: C, ) -> PyResult> where - C: ToPyObject, + C: IntoPyObject<'py>, { fn inner<'py>( object: &Bound<'py, PyAny>, @@ -164,20 +165,28 @@ impl PyWeakrefProxy { } let py = object.py(); - inner(object, callback.to_object(py).into_bound(py)) + inner( + object, + callback + .into_pyobject(py) + .map(BoundObject::into_any) + .map(BoundObject::into_bound) + .map_err(Into::into)?, + ) } /// Deprecated name for [`PyWeakrefProxy::new_with`]. #[deprecated(since = "0.23.0", note = "renamed to `PyWeakrefProxy::new_with`")] + #[allow(deprecated)] #[inline] pub fn new_bound_with<'py, C>( object: &Bound<'py, PyAny>, callback: C, ) -> PyResult> where - C: ToPyObject, + C: crate::ToPyObject, { - Self::new_with(object, callback) + Self::new_with(object, callback.to_object(object.py())) } } diff --git a/src/types/weakref/reference.rs b/src/types/weakref/reference.rs index cc8bc3d55f5..c75a54e9d70 100644 --- a/src/types/weakref/reference.rs +++ b/src/types/weakref/reference.rs @@ -1,8 +1,9 @@ use crate::err::PyResult; use crate::ffi_ptr_ext::FfiPtrExt; +use crate::prelude::IntoPyObject; use crate::py_result_ext::PyResultExt; use crate::types::{any::PyAny, PyNone}; -use crate::{ffi, Bound, ToPyObject}; +use crate::{ffi, Bound, BoundObject}; #[cfg(any(PyPy, GraalPy, Py_LIMITED_API))] use crate::type_object::PyTypeCheck; @@ -157,7 +158,7 @@ impl PyWeakrefReference { callback: C, ) -> PyResult> where - C: ToPyObject, + C: IntoPyObject<'py>, { fn inner<'py>( object: &Bound<'py, PyAny>, @@ -173,20 +174,28 @@ impl PyWeakrefReference { } let py = object.py(); - inner(object, callback.to_object(py).into_bound(py)) + inner( + object, + callback + .into_pyobject(py) + .map(BoundObject::into_any) + .map(BoundObject::into_bound) + .map_err(Into::into)?, + ) } /// Deprecated name for [`PyWeakrefReference::new_with`]. #[deprecated(since = "0.23.0", note = "renamed to `PyWeakrefReference::new_with`")] + #[allow(deprecated)] #[inline] pub fn new_bound_with<'py, C>( object: &Bound<'py, PyAny>, callback: C, ) -> PyResult> where - C: ToPyObject, + C: crate::ToPyObject, { - Self::new_with(object, callback) + Self::new_with(object, callback.to_object(object.py())) } } diff --git a/tests/test_class_conversion.rs b/tests/test_class_conversion.rs index ede8928f865..671dcd126b2 100644 --- a/tests/test_class_conversion.rs +++ b/tests/test_class_conversion.rs @@ -17,7 +17,7 @@ fn test_cloneable_pyclass() { let c = Cloneable { x: 10 }; Python::with_gil(|py| { - let py_c = Py::new(py, c.clone()).unwrap().to_object(py); + let py_c = Py::new(py, c.clone()).unwrap(); let c2: Cloneable = py_c.extract(py).unwrap(); assert_eq!(c, c2); @@ -69,8 +69,7 @@ fn test_polymorphic_container_stores_base_class() { inner: Py::new(py, BaseClass::default()).unwrap(), }, ) - .unwrap() - .to_object(py); + .unwrap(); py_assert!(py, p, "p.inner.foo() == 'BaseClass'"); }); @@ -85,8 +84,7 @@ fn test_polymorphic_container_stores_sub_class() { inner: Py::new(py, BaseClass::default()).unwrap(), }, ) - .unwrap() - .to_object(py); + .unwrap(); p.bind(py) .setattr( @@ -112,8 +110,7 @@ fn test_polymorphic_container_does_not_accept_other_types() { inner: Py::new(py, BaseClass::default()).unwrap(), }, ) - .unwrap() - .to_object(py); + .unwrap(); let setattr = |value: PyObject| p.bind(py).setattr("inner", value); diff --git a/tests/test_gc.rs b/tests/test_gc.rs index 1f55d91d496..bd592f6f867 100644 --- a/tests/test_gc.rs +++ b/tests/test_gc.rs @@ -121,7 +121,7 @@ fn gc_integration() { .unwrap(); let mut borrow = inst.borrow_mut(); - borrow.self_ref = inst.to_object(py); + borrow.self_ref = inst.clone().into_any().unbind(); py_run!(py, inst, "import gc; assert inst in gc.get_objects()"); }); @@ -274,18 +274,16 @@ fn gc_during_borrow() { // create an object and check that traversing it works normally // when it's not borrowed let cell = Bound::new(py, TraversableClass::new()).unwrap(); - let obj = cell.to_object(py); assert!(!cell.borrow().traversed.load(Ordering::Relaxed)); - traverse(obj.as_ptr(), novisit, std::ptr::null_mut()); + traverse(cell.as_ptr(), novisit, std::ptr::null_mut()); assert!(cell.borrow().traversed.load(Ordering::Relaxed)); // create an object and check that it is not traversed if the GC // is invoked while it is already borrowed mutably let cell2 = Bound::new(py, TraversableClass::new()).unwrap(); - let obj2 = cell2.to_object(py); let guard = cell2.borrow_mut(); assert!(!guard.traversed.load(Ordering::Relaxed)); - traverse(obj2.as_ptr(), novisit, std::ptr::null_mut()); + traverse(cell2.as_ptr(), novisit, std::ptr::null_mut()); assert!(!guard.traversed.load(Ordering::Relaxed)); drop(guard); } @@ -431,9 +429,8 @@ fn traverse_cannot_be_hijacked() { let traverse = get_type_traverse(ty.as_type_ptr()).unwrap(); let cell = Bound::new(py, HijackedTraverse::new()).unwrap(); - let obj = cell.to_object(py); assert_eq!(cell.borrow().traversed_and_hijacked(), (false, false)); - traverse(obj.as_ptr(), novisit, std::ptr::null_mut()); + traverse(cell.as_ptr(), novisit, std::ptr::null_mut()); assert_eq!(cell.borrow().traversed_and_hijacked(), (true, false)); }) } diff --git a/tests/test_getter_setter.rs b/tests/test_getter_setter.rs index d8cc3af20e6..144e3f2b7eb 100644 --- a/tests/test_getter_setter.rs +++ b/tests/test_getter_setter.rs @@ -228,8 +228,8 @@ fn cell_getter_setter() { cell_inner: Cell::new(10), }; Python::with_gil(|py| { - let inst = Py::new(py, c).unwrap().to_object(py); - let cell = Cell::new(20).to_object(py); + let inst = Py::new(py, c).unwrap(); + let cell = Cell::new(20i32).into_pyobject(py).unwrap(); py_run!(py, cell, "assert cell == 20"); py_run!(py, inst, "assert inst.cell_inner == 10"); @@ -255,7 +255,7 @@ fn borrowed_value_with_lifetime_of_self() { } Python::with_gil(|py| { - let inst = Py::new(py, BorrowedValue {}).unwrap().to_object(py); + let inst = Py::new(py, BorrowedValue {}).unwrap(); py_run!(py, inst, "assert inst.value == 'value'"); }); @@ -276,8 +276,7 @@ fn frozen_py_field_get() { value: "value".into_py(py), }, ) - .unwrap() - .to_object(py); + .unwrap(); py_run!(py, inst, "assert inst.value == 'value'"); }); diff --git a/tests/test_inheritance.rs b/tests/test_inheritance.rs index 2cce50bba25..7190dd49555 100644 --- a/tests/test_inheritance.rs +++ b/tests/test_inheritance.rs @@ -285,7 +285,7 @@ mod inheriting_native_type { Some(&dict) ); let err = res.unwrap_err(); - assert!(err.matches(py, &cls), "{}", err); + assert!(err.matches(py, &cls).unwrap(), "{}", err); // catching the exception in Python also works: py_run!( diff --git a/tests/test_methods.rs b/tests/test_methods.rs index eb099bc0aa5..82258ab7b67 100644 --- a/tests/test_methods.rs +++ b/tests/test_methods.rs @@ -4,6 +4,7 @@ use pyo3::prelude::*; use pyo3::py_run; use pyo3::types::PySequence; use pyo3::types::{IntoPyDict, PyDict, PyList, PySet, PyString, PyTuple, PyType}; +use pyo3::BoundObject; #[path = "../src/tests/common.rs"] mod common; @@ -213,24 +214,33 @@ impl MethSignature { test } #[pyo3(signature = (*args, **kwargs))] - fn get_kwargs( + fn get_kwargs<'py>( &self, - py: Python<'_>, - args: &Bound<'_, PyTuple>, - kwargs: Option<&Bound<'_, PyDict>>, - ) -> PyObject { - [args.to_object(py), kwargs.to_object(py)].to_object(py) + py: Python<'py>, + args: &Bound<'py, PyTuple>, + kwargs: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { + [ + args.as_any().clone(), + kwargs.into_pyobject(py)?.into_any().into_bound(), + ] + .into_pyobject(py) } #[pyo3(signature = (a, *args, **kwargs))] - fn get_pos_arg_kw( + fn get_pos_arg_kw<'py>( &self, - py: Python<'_>, + py: Python<'py>, a: i32, - args: &Bound<'_, PyTuple>, - kwargs: Option<&Bound<'_, PyDict>>, - ) -> PyObject { - [a.to_object(py), args.to_object(py), kwargs.to_object(py)].to_object(py) + args: &Bound<'py, PyTuple>, + kwargs: Option<&Bound<'py, PyDict>>, + ) -> PyResult> { + [ + a.into_pyobject(py)?.into_any().into_bound(), + args.as_any().clone(), + kwargs.into_pyobject(py)?.into_any().into_bound(), + ] + .into_pyobject(py) } #[pyo3(signature = (a, b, /))] @@ -274,8 +284,13 @@ impl MethSignature { py: Python<'_>, a: i32, kwargs: Option<&Bound<'_, PyDict>>, - ) -> PyObject { - [a.to_object(py), kwargs.to_object(py)].to_object(py) + ) -> PyResult { + [ + a.into_pyobject(py)?.into_any().into_bound(), + kwargs.into_pyobject(py)?.into_any().into_bound(), + ] + .into_pyobject(py) + .map(BoundObject::unbind) } #[pyo3(signature = (a=0, /, **kwargs))] @@ -284,8 +299,13 @@ impl MethSignature { py: Python<'_>, a: i32, kwargs: Option<&Bound<'_, PyDict>>, - ) -> PyObject { - [a.to_object(py), kwargs.to_object(py)].to_object(py) + ) -> PyResult { + [ + a.into_pyobject(py)?.into_any().into_bound(), + kwargs.into_pyobject(py)?.into_any().into_bound(), + ] + .into_pyobject(py) + .map(BoundObject::unbind) } #[pyo3(signature = (*, a = 2, b = 3))] @@ -309,8 +329,11 @@ impl MethSignature { py: Python<'_>, args: &Bound<'_, PyTuple>, a: i32, - ) -> PyObject { - (args, a).to_object(py) + ) -> PyResult { + (args, a) + .into_pyobject(py) + .map(BoundObject::into_any) + .map(BoundObject::unbind) } #[pyo3(signature = (a, b = 2, *, c = 3))] @@ -324,8 +347,18 @@ impl MethSignature { } #[pyo3(signature = (a, **kwargs))] - fn get_pos_kw(&self, py: Python<'_>, a: i32, kwargs: Option<&Bound<'_, PyDict>>) -> PyObject { - [a.to_object(py), kwargs.to_object(py)].to_object(py) + fn get_pos_kw( + &self, + py: Python<'_>, + a: i32, + kwargs: Option<&Bound<'_, PyDict>>, + ) -> PyResult { + [ + a.into_pyobject(py)?.into_any().into_bound(), + kwargs.into_pyobject(py)?.into_any().into_bound(), + ] + .into_pyobject(py) + .map(BoundObject::unbind) } // "args" can be anything that can be extracted from PyTuple diff --git a/tests/test_module.rs b/tests/test_module.rs index c33a8a27ee5..7b97fb3a889 100644 --- a/tests/test_module.rs +++ b/tests/test_module.rs @@ -5,6 +5,7 @@ use pyo3::prelude::*; use pyo3::py_run; use pyo3::types::PyString; use pyo3::types::{IntoPyDict, PyDict, PyTuple}; +use pyo3::BoundObject; use pyo3_ffi::c_str; #[path = "../src/tests/common.rs"] @@ -173,13 +174,12 @@ fn test_module_from_code_bound() { let add_func = adder_mod .getattr("add") - .expect("Add function should be in the module") - .to_object(py); + .expect("Add function should be in the module"); let ret_value: i32 = add_func - .call1(py, (1, 2)) + .call1((1, 2)) .expect("A value should be returned") - .extract(py) + .extract() .expect("The value should be able to be converted to an i32"); assert_eq!(ret_value, 3); @@ -321,14 +321,19 @@ fn test_module_nesting() { // Test that argument parsing specification works for pyfunctions #[pyfunction(signature = (a=5, *args))] -fn ext_vararg_fn(py: Python<'_>, a: i32, args: &Bound<'_, PyTuple>) -> PyObject { - [a.to_object(py), args.into_py(py)].to_object(py) +fn ext_vararg_fn(py: Python<'_>, a: i32, args: &Bound<'_, PyTuple>) -> PyResult { + [ + a.into_pyobject(py)?.into_any().into_bound(), + args.as_any().clone(), + ] + .into_pyobject(py) + .map(BoundObject::unbind) } #[pymodule] fn vararg_module(m: &Bound<'_, PyModule>) -> PyResult<()> { #[pyfn(m, signature = (a=5, *args))] - fn int_vararg_fn(py: Python<'_>, a: i32, args: &Bound<'_, PyTuple>) -> PyObject { + fn int_vararg_fn(py: Python<'_>, a: i32, args: &Bound<'_, PyTuple>) -> PyResult { ext_vararg_fn(py, a, args) } diff --git a/tests/test_sequence.rs b/tests/test_sequence.rs index fd7e9eb01c6..484e519fd21 100644 --- a/tests/test_sequence.rs +++ b/tests/test_sequence.rs @@ -264,7 +264,10 @@ struct GenericList { fn test_generic_list_get() { Python::with_gil(|py| { let list: PyObject = GenericList { - items: [1, 2, 3].iter().map(|i| i.to_object(py)).collect(), + items: [1i32, 2, 3] + .iter() + .map(|i| i.into_pyobject(py).unwrap().into_any().unbind()) + .collect(), } .into_py(py); diff --git a/tests/test_various.rs b/tests/test_various.rs index 27192aba3bb..a8aa6b7a71f 100644 --- a/tests/test_various.rs +++ b/tests/test_various.rs @@ -132,9 +132,9 @@ fn test_pickle() { pub fn __reduce__<'py>( slf: &Bound<'py, Self>, py: Python<'py>, - ) -> PyResult<(PyObject, Bound<'py, PyTuple>, PyObject)> { - let cls = slf.to_object(py).getattr(py, "__class__")?; - let dict = slf.to_object(py).getattr(py, "__dict__")?; + ) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyTuple>, Bound<'py, PyAny>)> { + let cls = slf.getattr("__class__")?; + let dict = slf.getattr("__dict__")?; Ok((cls, PyTuple::empty(py), dict)) } }