deprecate `PyCell::new` in favor of `Py::new` or `Bound::new` (#3872)

* deprecate `PyCell::new` in favor of `Py::new` or `Bound::new`

* update deprecation warning

Co-authored-by: David Hewitt <mail@davidhewitt.dev>

---------

Co-authored-by: David Hewitt <mail@davidhewitt.dev>
This commit is contained in:
Icxolu 2024-02-20 08:45:47 +01:00 committed by GitHub
parent a93900686e
commit 61bc02d927
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 104 additions and 81 deletions

View File

@ -216,6 +216,7 @@ struct MyClass {
num: i32,
}
Python::with_gil(|py| {
# #[allow(deprecated)]
let obj = PyCell::new(py, MyClass { num: 3 }).unwrap();
{
let obj_ref = obj.borrow(); // Get PyRef
@ -397,7 +398,7 @@ impl SubSubClass {
}
}
# Python::with_gil(|py| {
# let subsub = pyo3::PyCell::new(py, SubSubClass::new()).unwrap();
# let subsub = pyo3::Py::new(py, SubSubClass::new()).unwrap();
# pyo3::py_run!(py, subsub, "assert subsub.method3() == 3000");
# let subsub = SubSubClass::factory_method(py, 2).unwrap();
# let subsubsub = SubSubClass::factory_method(py, 3).unwrap();
@ -441,7 +442,7 @@ impl DictWithCounter {
}
}
# Python::with_gil(|py| {
# let cnt = pyo3::PyCell::new(py, DictWithCounter::new()).unwrap();
# let cnt = pyo3::Py::new(py, DictWithCounter::new()).unwrap();
# pyo3::py_run!(py, cnt, "cnt.set('abc', 10); assert cnt['abc'] == 10")
# });
# }

View File

@ -217,8 +217,8 @@ impl Number {
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let x = PyCell::new(py, Number(4))?;
# let y = PyCell::new(py, Number(4))?;
# let x = &Bound::new(py, Number(4))?.into_any();
# let y = &Bound::new(py, Number(4))?.into_any();
# assert!(x.eq(y)?);
# assert!(!x.ne(y)?);
# Ok(())

View File

@ -207,7 +207,7 @@ impl Container {
# Python::with_gil(|py| {
# let container = Container { iter: vec![1, 2, 3, 4] };
# let inst = pyo3::PyCell::new(py, container).unwrap();
# let inst = pyo3::Py::new(py, container).unwrap();
# pyo3::py_run!(py, inst, "assert list(inst) == [1, 2, 3, 4]");
# pyo3::py_run!(py, inst, "assert list(iter(iter(inst))) == [1, 2, 3, 4]");
# });

View File

@ -1317,7 +1317,7 @@ impl Names {
}
}
# Python::with_gil(|py| {
# let names = PyCell::new(py, Names::new()).unwrap();
# let names = Py::new(py, Names::new()).unwrap();
# pyo3::py_run!(py, names, r"
# try:
# names.merge(names)
@ -1352,7 +1352,7 @@ let obj_ref = PyRef::new(py, MyClass {}).unwrap();
```
After:
```rust
```rust,ignore
# use pyo3::prelude::*;
# #[pyclass]
# struct MyClass {}

View File

@ -206,7 +206,7 @@ Python::with_gil(|py| {
id: 34,
name: "Yu".to_string(),
};
let userdata = PyCell::new(py, userdata).unwrap();
let userdata = Py::new(py, userdata).unwrap();
let userdata_as_tuple = (34, "Yu");
py_run!(py, userdata userdata_as_tuple, r#"
assert repr(userdata) == "User Yu(id: 34)"

View File

@ -245,6 +245,7 @@ so it also exposes all of the methods on `PyAny`.
# use pyo3::prelude::*;
# #[pyclass] struct MyClass { }
# Python::with_gil(|py| -> PyResult<()> {
# #[allow(deprecated)]
let cell: &PyCell<MyClass> = PyCell::new(py, MyClass {})?;
// To PyRef<T> with .borrow() or .try_borrow()
@ -265,6 +266,7 @@ let _: &mut MyClass = &mut *py_ref_mut;
# use pyo3::prelude::*;
# #[pyclass] struct MyClass { }
# Python::with_gil(|py| -> PyResult<()> {
# #[allow(deprecated)]
let cell: &PyCell<MyClass> = PyCell::new(py, MyClass {})?;
// Use methods from PyAny on PyCell<T> with Deref implementation

View File

@ -45,7 +45,7 @@
/// }
///
/// Python::with_gil(|py| {
/// let time = PyCell::new(py, Time {hour: 8, minute: 43, second: 16}).unwrap();
/// let time = Py::new(py, Time {hour: 8, minute: 43, second: 16}).unwrap();
/// let time_as_tuple = (8, 43, 16);
/// py_run!(py, time time_as_tuple, r#"
/// assert time.hour == 8

View File

@ -249,6 +249,7 @@ unsafe impl<T, U> PyLayout<T> for PyCellBase<U> where U: PySizedLayout<T> {}
///
/// # fn main() -> PyResult<()> {
/// Python::with_gil(|py| {
/// # #[allow(deprecated)]
/// let n = PyCell::new(py, Number { inner: 0 })?;
///
/// let n_mutable: &mut Number = &mut n.borrow_mut();
@ -284,6 +285,13 @@ impl<T: PyClass> PyCell<T> {
///
/// In cases where the value in the cell does not need to be accessed immediately after
/// creation, consider [`Py::new`](crate::Py::new) as a more efficient alternative.
#[cfg_attr(
not(feature = "gil-refs"),
deprecated(
since = "0.21.0",
note = "part of the deprecated GIL Ref API; to migrate use `Bound::new(py, value)` or `Py::new(py, value)` instead of `PyCell::new(py, value)`"
)
)]
pub fn new(py: Python<'_>, value: impl Into<PyClassInitializer<T>>) -> PyResult<&Self> {
unsafe {
let initializer = value.into();
@ -332,6 +340,7 @@ impl<T: PyClass> PyCell<T> {
/// struct Class {}
///
/// Python::with_gil(|py| {
/// # #[allow(deprecated)]
/// let c = PyCell::new(py, Class {}).unwrap();
/// {
/// let m = c.borrow_mut();
@ -371,6 +380,7 @@ impl<T: PyClass> PyCell<T> {
/// #[pyclass]
/// struct Class {}
/// Python::with_gil(|py| {
/// # #[allow(deprecated)]
/// let c = PyCell::new(py, Class {}).unwrap();
/// {
/// let m = c.borrow();
@ -406,6 +416,7 @@ impl<T: PyClass> PyCell<T> {
/// #[pyclass]
/// struct Class {}
/// Python::with_gil(|py| {
/// # #[allow(deprecated)]
/// let c = PyCell::new(py, Class {}).unwrap();
///
/// {
@ -448,6 +459,7 @@ impl<T: PyClass> PyCell<T> {
/// Python::with_gil(|py| {
/// let counter = FrozenCounter { value: AtomicUsize::new(0) };
///
/// # #[allow(deprecated)]
/// let cell = PyCell::new(py, counter).unwrap();
///
/// cell.get().value.fetch_add(1, Ordering::Relaxed);
@ -640,7 +652,7 @@ impl<T: PyClass + fmt::Debug> fmt::Debug for PyCell<T> {
/// }
/// }
/// # Python::with_gil(|py| {
/// # let sub = PyCell::new(py, Child::new()).unwrap();
/// # let sub = Py::new(py, Child::new()).unwrap();
/// # pyo3::py_run!(py, sub, "assert sub.format() == 'Caterpillar(base: Butterfly, cnt: 3)'");
/// # });
/// ```
@ -739,7 +751,7 @@ where
/// }
/// }
/// # Python::with_gil(|py| {
/// # let sub = PyCell::new(py, Sub::new()).unwrap();
/// # let sub = Py::new(py, Sub::new()).unwrap();
/// # pyo3::py_run!(py, sub, "assert sub.name() == 'base1 base2 sub'")
/// # });
/// ```
@ -1069,6 +1081,7 @@ mod tests {
#[test]
fn pycell_replace() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
assert_eq!(*cell.borrow(), SomeClass(0));
@ -1082,6 +1095,7 @@ mod tests {
#[should_panic(expected = "Already borrowed: PyBorrowMutError")]
fn pycell_replace_panic() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
let _guard = cell.borrow();
@ -1092,6 +1106,7 @@ mod tests {
#[test]
fn pycell_replace_with() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
assert_eq!(*cell.borrow(), SomeClass(0));
@ -1108,6 +1123,7 @@ mod tests {
#[should_panic(expected = "Already borrowed: PyBorrowMutError")]
fn pycell_replace_with_panic() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
let _guard = cell.borrow();
@ -1118,7 +1134,9 @@ mod tests {
#[test]
fn pycell_swap() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
#[allow(deprecated)]
let cell2 = PyCell::new(py, SomeClass(123)).unwrap();
assert_eq!(*cell.borrow(), SomeClass(0));
assert_eq!(*cell2.borrow(), SomeClass(123));
@ -1133,7 +1151,9 @@ mod tests {
#[should_panic(expected = "Already borrowed: PyBorrowMutError")]
fn pycell_swap_panic() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
#[allow(deprecated)]
let cell2 = PyCell::new(py, SomeClass(123)).unwrap();
let _guard = cell.borrow();
@ -1145,7 +1165,9 @@ mod tests {
#[should_panic(expected = "Already borrowed: PyBorrowMutError")]
fn pycell_swap_panic_other_borrowed() {
Python::with_gil(|py| {
#[allow(deprecated)]
let cell = PyCell::new(py, SomeClass(0)).unwrap();
#[allow(deprecated)]
let cell2 = PyCell::new(py, SomeClass(123)).unwrap();
let _guard = cell2.borrow();
@ -1156,7 +1178,7 @@ mod tests {
#[test]
fn test_as_ptr() {
Python::with_gil(|py| {
let cell = PyCell::new(py, SomeClass(0)).unwrap();
let cell = Bound::new(py, SomeClass(0)).unwrap();
let ptr = cell.as_ptr();
assert_eq!(cell.borrow().as_ptr(), ptr);
@ -1167,7 +1189,7 @@ mod tests {
#[test]
fn test_into_ptr() {
Python::with_gil(|py| {
let cell = PyCell::new(py, SomeClass(0)).unwrap();
let cell = Bound::new(py, SomeClass(0)).unwrap();
let ptr = cell.as_ptr();
assert_eq!(cell.borrow().into_ptr(), ptr);

View File

@ -43,7 +43,7 @@ impl UnaryArithmetic {
#[test]
fn unary_arithmetic() {
Python::with_gil(|py| {
let c = PyCell::new(py, UnaryArithmetic::new(2.7)).unwrap();
let c = Py::new(py, UnaryArithmetic::new(2.7)).unwrap();
py_run!(py, c, "assert repr(-c) == 'UA(-2.7)'");
py_run!(py, c, "assert repr(+c) == 'UA(2.7)'");
py_run!(py, c, "assert repr(abs(c)) == 'UA(2.7)'");
@ -77,7 +77,7 @@ impl Indexable {
#[test]
fn indexable() {
Python::with_gil(|py| {
let i = PyCell::new(py, Indexable(5)).unwrap();
let i = Py::new(py, Indexable(5)).unwrap();
py_run!(py, i, "assert int(i) == 5");
py_run!(py, i, "assert [0, 1, 2, 3, 4, 5][i] == 5");
py_run!(py, i, "assert float(i) == 5.0");
@ -137,7 +137,7 @@ impl InPlaceOperations {
fn inplace_operations() {
Python::with_gil(|py| {
let init = |value, code| {
let c = PyCell::new(py, InPlaceOperations { value }).unwrap();
let c = Py::new(py, InPlaceOperations { value }).unwrap();
py_run!(py, c, code);
};
@ -210,7 +210,7 @@ impl BinaryArithmetic {
#[test]
fn binary_arithmetic() {
Python::with_gil(|py| {
let c = PyCell::new(py, BinaryArithmetic {}).unwrap();
let c = Py::new(py, BinaryArithmetic {}).unwrap();
py_run!(py, c, "assert c + c == 'BA + BA'");
py_run!(py, c, "assert c.__add__(c) == 'BA + BA'");
py_run!(py, c, "assert c + 1 == 'BA + 1'");
@ -238,7 +238,7 @@ fn binary_arithmetic() {
py_run!(py, c, "assert pow(c, 1, 100) == 'BA ** 1 (mod: Some(100))'");
let c: Bound<'_, PyAny> = c.extract().unwrap();
let c: Bound<'_, PyAny> = c.extract(py).unwrap();
assert_py_eq!(c.add(&c).unwrap(), "BA + BA");
assert_py_eq!(c.sub(&c).unwrap(), "BA - BA");
assert_py_eq!(c.mul(&c).unwrap(), "BA * BA");
@ -297,7 +297,7 @@ impl RhsArithmetic {
#[test]
fn rhs_arithmetic() {
Python::with_gil(|py| {
let c = PyCell::new(py, RhsArithmetic {}).unwrap();
let c = Py::new(py, RhsArithmetic {}).unwrap();
py_run!(py, c, "assert c.__radd__(1) == '1 + RA'");
py_run!(py, c, "assert 1 + c == '1 + RA'");
py_run!(py, c, "assert c.__rsub__(1) == '1 - RA'");
@ -426,7 +426,7 @@ impl LhsAndRhs {
#[test]
fn lhs_fellback_to_rhs() {
Python::with_gil(|py| {
let c = PyCell::new(py, LhsAndRhs {}).unwrap();
let c = Py::new(py, LhsAndRhs {}).unwrap();
// If the light hand value is `LhsAndRhs`, LHS is used.
py_run!(py, c, "assert c + 1 == 'LR + 1'");
py_run!(py, c, "assert c - 1 == 'LR - 1'");
@ -494,7 +494,7 @@ impl RichComparisons2 {
#[test]
fn rich_comparisons() {
Python::with_gil(|py| {
let c = PyCell::new(py, RichComparisons {}).unwrap();
let c = Py::new(py, RichComparisons {}).unwrap();
py_run!(py, c, "assert (c < c) == 'RC < RC'");
py_run!(py, c, "assert (c < 1) == 'RC < 1'");
py_run!(py, c, "assert (1 < c) == 'RC > 1'");
@ -519,7 +519,7 @@ fn rich_comparisons() {
#[test]
fn rich_comparisons_python_3_type_error() {
Python::with_gil(|py| {
let c2 = PyCell::new(py, RichComparisons2 {}).unwrap();
let c2 = Py::new(py, RichComparisons2 {}).unwrap();
py_expect_exception!(py, c2, "c2 < c2", PyTypeError);
py_expect_exception!(py, c2, "c2 < 1", PyTypeError);
py_expect_exception!(py, c2, "1 < c2", PyTypeError);
@ -620,7 +620,7 @@ mod return_not_implemented {
fn _test_binary_dunder(dunder: &str) {
Python::with_gil(|py| {
let c2 = PyCell::new(py, RichComparisonToSelf {}).unwrap();
let c2 = Py::new(py, RichComparisonToSelf {}).unwrap();
py_run!(
py,
c2,
@ -636,7 +636,7 @@ mod return_not_implemented {
_test_binary_dunder(dunder);
Python::with_gil(|py| {
let c2 = PyCell::new(py, RichComparisonToSelf {}).unwrap();
let c2 = Py::new(py, RichComparisonToSelf {}).unwrap();
py_expect_exception!(
py,
c2,

View File

@ -376,7 +376,7 @@ struct DunderDictSupport {
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
fn dunder_dict_support() {
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Py::new(
py,
DunderDictSupport {
_pad: *b"DEADBEEFDEADBEEFDEADBEEFDEADBEEF",
@ -399,7 +399,7 @@ fn dunder_dict_support() {
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_10)), ignore)]
fn access_dunder_dict() {
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Py::new(
py,
DunderDictSupport {
_pad: *b"DEADBEEFDEADBEEFDEADBEEFDEADBEEF",
@ -427,7 +427,7 @@ struct InheritDict {
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
fn inherited_dict() {
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Py::new(
py,
(
InheritDict { _value: 0 },
@ -458,7 +458,7 @@ struct WeakRefDunderDictSupport {
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
fn weakref_dunder_dict_support() {
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Py::new(
py,
WeakRefDunderDictSupport {
_pad: *b"DEADBEEFDEADBEEFDEADBEEFDEADBEEF",
@ -482,7 +482,7 @@ struct WeakRefSupport {
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
fn weakref_support() {
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Py::new(
py,
WeakRefSupport {
_pad: *b"DEADBEEFDEADBEEFDEADBEEFDEADBEEF",
@ -507,7 +507,7 @@ struct InheritWeakRef {
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_9)), ignore)]
fn inherited_weakref() {
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Py::new(
py,
(
InheritWeakRef { _value: 0 },
@ -539,7 +539,7 @@ fn access_frozen_class_without_gil() {
value: AtomicUsize::new(0),
};
let cell = PyCell::new(py, counter).unwrap();
let cell = Bound::new(py, counter).unwrap();
cell.get().value.fetch_add(1, Ordering::Relaxed);

View File

@ -63,7 +63,7 @@ struct PolymorphicContainer {
#[test]
fn test_polymorphic_container_stores_base_class() {
Python::with_gil(|py| {
let p = PyCell::new(
let p = Py::new(
py,
PolymorphicContainer {
inner: Py::new(py, BaseClass::default()).unwrap(),
@ -79,7 +79,7 @@ fn test_polymorphic_container_stores_base_class() {
#[test]
fn test_polymorphic_container_stores_sub_class() {
Python::with_gil(|py| {
let p = PyCell::new(
let p = Py::new(
py,
PolymorphicContainer {
inner: Py::new(py, BaseClass::default()).unwrap(),
@ -91,7 +91,7 @@ fn test_polymorphic_container_stores_sub_class() {
p.bind(py)
.setattr(
"inner",
PyCell::new(
Py::new(
py,
PyClassInitializer::from(BaseClass::default()).add_subclass(SubClass {}),
)
@ -106,7 +106,7 @@ fn test_polymorphic_container_stores_sub_class() {
#[test]
fn test_polymorphic_container_does_not_accept_other_types() {
Python::with_gil(|py| {
let p = PyCell::new(
let p = Py::new(
py,
PolymorphicContainer {
inner: Py::new(py, BaseClass::default()).unwrap(),
@ -126,7 +126,7 @@ fn test_polymorphic_container_does_not_accept_other_types() {
#[test]
fn test_pyref_as_base() {
Python::with_gil(|py| {
let cell = PyCell::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();
let cell = Bound::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();
// First try PyRefMut
let sub: PyRefMut<'_, SubClass> = cell.borrow_mut();
@ -146,12 +146,14 @@ fn test_pyref_as_base() {
#[test]
fn test_pycell_deref() {
Python::with_gil(|py| {
let cell = PyCell::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();
let cell = Bound::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();
// Should be able to deref as PyAny
// FIXME: This deref does _not_ work
assert_eq!(
cell.call_method0("foo")
.and_then(PyAny::extract::<&str>)
cell.as_any()
.call_method0("foo")
.and_then(|e| e.extract::<&str>())
.unwrap(),
"SubClass"
);

View File

@ -222,12 +222,8 @@ impl NewExisting {
static PRE_BUILT: GILOnceCell<[pyo3::Py<NewExisting>; 2]> = GILOnceCell::new();
let existing = PRE_BUILT.get_or_init(py, || {
[
pyo3::PyCell::new(py, NewExisting { num: 0 })
.unwrap()
.into(),
pyo3::PyCell::new(py, NewExisting { num: 1 })
.unwrap()
.into(),
pyo3::Py::new(py, NewExisting { num: 0 }).unwrap(),
pyo3::Py::new(py, NewExisting { num: 1 }).unwrap(),
]
});
@ -235,9 +231,7 @@ impl NewExisting {
return existing[val].clone_ref(py);
}
pyo3::PyCell::new(py, NewExisting { num: val })
.unwrap()
.into()
pyo3::Py::new(py, NewExisting { num: val }).unwrap()
}
}

View File

@ -99,7 +99,7 @@ fn gc_integration() {
let drop_called = Arc::new(AtomicBool::new(false));
Python::with_gil(|py| {
let inst = PyCell::new(
let inst = Bound::new(
py,
GcIntegration {
self_ref: py.None(),
@ -260,7 +260,7 @@ fn gc_during_borrow() {
// create an object and check that traversing it works normally
// when it's not borrowed
let cell = PyCell::new(py, TraversableClass::new()).unwrap();
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());
@ -268,7 +268,7 @@ fn gc_during_borrow() {
// create an object and check that it is not traversed if the GC
// is invoked while it is already borrowed mutably
let cell2 = PyCell::new(py, TraversableClass::new()).unwrap();
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));
@ -417,7 +417,7 @@ fn traverse_cannot_be_hijacked() {
let ty = py.get_type_bound::<HijackedTraverse>();
let traverse = get_type_traverse(ty.as_type_ptr()).unwrap();
let cell = PyCell::new(py, HijackedTraverse::new()).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());

View File

@ -81,7 +81,7 @@ fn inheritance_with_new_methods() {
#[test]
fn call_base_and_sub_methods() {
Python::with_gil(|py| {
let obj = PyCell::new(py, SubClass::new()).unwrap();
let obj = Py::new(py, SubClass::new()).unwrap();
py_run!(
py,
obj,
@ -96,7 +96,7 @@ fn call_base_and_sub_methods() {
#[test]
fn mutation_fails() {
Python::with_gil(|py| {
let obj = PyCell::new(py, SubClass::new()).unwrap();
let obj = Py::new(py, SubClass::new()).unwrap();
let global = [("obj", obj)].into_py_dict_bound(py);
let e = py
.run_bound(
@ -202,7 +202,7 @@ mod inheriting_native_type {
}
Python::with_gil(|py| {
let set_sub = pyo3::PyCell::new(py, SetWithName::new()).unwrap();
let set_sub = pyo3::Py::new(py, SetWithName::new()).unwrap();
py_run!(
py,
set_sub,
@ -229,7 +229,7 @@ mod inheriting_native_type {
#[test]
fn inherit_dict() {
Python::with_gil(|py| {
let dict_sub = pyo3::PyCell::new(py, DictWithName::new()).unwrap();
let dict_sub = pyo3::Py::new(py, DictWithName::new()).unwrap();
py_run!(
py,
dict_sub,

View File

@ -28,7 +28,7 @@ impl InstanceMethod {
#[test]
fn instance_method() {
Python::with_gil(|py| {
let obj = PyCell::new(py, InstanceMethod { member: 42 }).unwrap();
let obj = Bound::new(py, InstanceMethod { member: 42 }).unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.method(), 42);
py_assert!(py, obj, "obj.method() == 42");
@ -52,7 +52,7 @@ impl InstanceMethodWithArgs {
#[test]
fn instance_method_with_args() {
Python::with_gil(|py| {
let obj = PyCell::new(py, InstanceMethodWithArgs { member: 7 }).unwrap();
let obj = Bound::new(py, InstanceMethodWithArgs { member: 7 }).unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.method(6), 42);
py_assert!(py, obj, "obj.method(3) == 21");
@ -710,7 +710,7 @@ impl MethodWithLifeTime {
#[test]
fn method_with_lifetime() {
Python::with_gil(|py| {
let obj = PyCell::new(py, MethodWithLifeTime {}).unwrap();
let obj = Py::new(py, MethodWithLifeTime {}).unwrap();
py_run!(
py,
obj,
@ -758,8 +758,8 @@ impl MethodWithPyClassArg {
#[test]
fn method_with_pyclassarg() {
Python::with_gil(|py| {
let obj1 = PyCell::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let obj2 = PyCell::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let obj1 = Py::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let obj2 = Py::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let d = [("obj1", obj1), ("obj2", obj2)].into_py_dict_bound(py);
py_run!(py, *d, "obj = obj1.add(obj2); assert obj.value == 20");
py_run!(py, *d, "obj = obj1.add_pyref(obj2); assert obj.value == 20");

View File

@ -447,7 +447,7 @@ impl SetItem {
#[test]
fn setitem() {
Python::with_gil(|py| {
let c = PyCell::new(py, SetItem { key: 0, val: 0 }).unwrap();
let c = Bound::new(py, SetItem { key: 0, val: 0 }).unwrap();
py_run!(py, c, "c[1] = 2");
{
let c = c.borrow();
@ -473,7 +473,7 @@ impl DelItem {
#[test]
fn delitem() {
Python::with_gil(|py| {
let c = PyCell::new(py, DelItem { key: 0 }).unwrap();
let c = Bound::new(py, DelItem { key: 0 }).unwrap();
py_run!(py, c, "del c[1]");
{
let c = c.borrow();
@ -502,7 +502,7 @@ impl SetDelItem {
#[test]
fn setdelitem() {
Python::with_gil(|py| {
let c = PyCell::new(py, SetDelItem { val: None }).unwrap();
let c = Bound::new(py, SetDelItem { val: None }).unwrap();
py_run!(py, c, "c[1] = 2");
{
let c = c.borrow();
@ -580,7 +580,7 @@ impl ClassWithGetAttr {
#[test]
fn getattr_doesnt_override_member() {
Python::with_gil(|py| {
let inst = PyCell::new(py, ClassWithGetAttr { data: 4 }).unwrap();
let inst = Py::new(py, ClassWithGetAttr { data: 4 }).unwrap();
py_assert!(py, inst, "inst.data == 4");
py_assert!(py, inst, "inst.a == 8");
});
@ -602,7 +602,7 @@ impl ClassWithGetAttribute {
#[test]
fn getattribute_overrides_member() {
Python::with_gil(|py| {
let inst = PyCell::new(py, ClassWithGetAttribute { data: 4 }).unwrap();
let inst = Py::new(py, ClassWithGetAttribute { data: 4 }).unwrap();
py_assert!(py, inst, "inst.data == 8");
py_assert!(py, inst, "inst.y == 8");
});
@ -635,7 +635,7 @@ impl ClassWithGetAttrAndGetAttribute {
#[test]
fn getattr_and_getattribute() {
Python::with_gil(|py| {
let inst = PyCell::new(py, ClassWithGetAttrAndGetAttribute).unwrap();
let inst = Py::new(py, ClassWithGetAttrAndGetAttribute).unwrap();
py_assert!(py, inst, "inst.exists == 42");
py_assert!(py, inst, "inst.lucky == 57");
py_expect_exception!(py, inst, "inst.error", PyValueError);

View File

@ -111,7 +111,7 @@ fn test_clone_ref() {
#[test]
fn test_nested_iter_reset() {
Python::with_gil(|py| {
let reader = PyCell::new(py, reader()).unwrap();
let reader = Bound::new(py, reader()).unwrap();
py_assert!(
py,
reader,

View File

@ -268,7 +268,7 @@ fn test_generic_list_get() {
#[test]
fn test_generic_list_set() {
Python::with_gil(|py| {
let list = PyCell::new(py, GenericList { items: vec![] }).unwrap();
let list = Bound::new(py, GenericList { items: vec![] }).unwrap();
py_run!(py, list, "list.items = [1, 2, 3]");
assert!(list
@ -304,7 +304,7 @@ impl OptionList {
fn test_option_list_get() {
// Regression test for #798
Python::with_gil(|py| {
let list = PyCell::new(
let list = Py::new(
py,
OptionList {
items: vec![Some(1), None],
@ -321,31 +321,33 @@ fn test_option_list_get() {
#[test]
fn sequence_is_not_mapping() {
Python::with_gil(|py| {
let list = PyCell::new(
let list = Bound::new(
py,
OptionList {
items: vec![Some(1), None],
},
)
.unwrap();
.unwrap()
.into_any();
PySequence::register::<OptionList>(py).unwrap();
assert!(list.as_ref().downcast::<PyMapping>().is_err());
assert!(list.as_ref().downcast::<PySequence>().is_ok());
assert!(list.downcast::<PyMapping>().is_err());
assert!(list.downcast::<PySequence>().is_ok());
})
}
#[test]
fn sequence_length() {
Python::with_gil(|py| {
let list = PyCell::new(
let list = Bound::new(
py,
OptionList {
items: vec![Some(1), None],
},
)
.unwrap();
.unwrap()
.into_any();
assert_eq!(list.len().unwrap(), 2);
assert_eq!(unsafe { ffi::PySequence_Length(list.as_ptr()) }, 2);

View File

@ -79,8 +79,8 @@ struct SimplePyClass {}
fn intopytuple_pyclass() {
Python::with_gil(|py| {
let tup = (
PyCell::new(py, SimplePyClass {}).unwrap(),
PyCell::new(py, SimplePyClass {}).unwrap(),
Py::new(py, SimplePyClass {}).unwrap(),
Py::new(py, SimplePyClass {}).unwrap(),
);
py_assert!(py, tup, "type(tup[0]).__name__ == 'SimplePyClass'");
py_assert!(py, tup, "type(tup[0]).__name__ == type(tup[1]).__name__");
@ -102,8 +102,8 @@ fn pytuple_pyclass_iter() {
let tup = PyTuple::new_bound(
py,
[
PyCell::new(py, SimplePyClass {}).unwrap(),
PyCell::new(py, SimplePyClass {}).unwrap(),
Py::new(py, SimplePyClass {}).unwrap(),
Py::new(py, SimplePyClass {}).unwrap(),
]
.iter(),
);
@ -150,7 +150,7 @@ fn test_pickle() {
let module = PyModule::new(py, "test_module").unwrap();
module.add_class::<PickleSupport>().unwrap();
add_module(py, module).unwrap();
let inst = PyCell::new(py, PickleSupport {}).unwrap();
let inst = Py::new(py, PickleSupport {}).unwrap();
py_run!(
py,
inst,