diff --git a/CHANGELOG.md b/CHANGELOG.md index dc3194a6..c2ea9293 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Removed + * `PyToken` was removed due to unsoundness (See [#94](https://github.com/PyO3/pyo3/issues/94)). * Removed the unnecessary type parameter from `PyObjectAlloc` ## [0.5.0] - 2018-11-11 diff --git a/examples/rustapi_module/src/datetime.rs b/examples/rustapi_module/src/datetime.rs index 7387fb5c..98cf376c 100644 --- a/examples/rustapi_module/src/datetime.rs +++ b/examples/rustapi_module/src/datetime.rs @@ -186,7 +186,7 @@ pub struct TzClass {} impl TzClass { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| TzClass {}) + obj.init(|| TzClass {}) } fn utcoffset(&self, py: Python, _dt: &PyDateTime) -> PyResult> { diff --git a/examples/rustapi_module/src/othermod.rs b/examples/rustapi_module/src/othermod.rs index 922d42c0..d42a58d4 100644 --- a/examples/rustapi_module/src/othermod.rs +++ b/examples/rustapi_module/src/othermod.rs @@ -13,7 +13,7 @@ pub struct ModClass { impl ModClass { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| ModClass { + obj.init(|| ModClass { _somefield: String::from("contents"), }) } diff --git a/examples/rustapi_module/src/subclassing.rs b/examples/rustapi_module/src/subclassing.rs index 73543cfe..2dcddce8 100644 --- a/examples/rustapi_module/src/subclassing.rs +++ b/examples/rustapi_module/src/subclassing.rs @@ -9,7 +9,7 @@ pub struct Subclassable {} impl Subclassable { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| Subclassable {}) + obj.init(|| Subclassable {}) } } diff --git a/examples/word-count/src/lib.rs b/examples/word-count/src/lib.rs index 5785a181..05ee9956 100644 --- a/examples/word-count/src/lib.rs +++ b/examples/word-count/src/lib.rs @@ -21,7 +21,7 @@ struct WordCounter { impl WordCounter { #[new] fn __new__(obj: &PyRawObject, path: String) -> PyResult<()> { - obj.init(|_| WordCounter { + obj.init(|| WordCounter { path: PathBuf::from(path), }) } diff --git a/guide/src/class.md b/guide/src/class.md index b52b46fe..d6566ca2 100644 --- a/guide/src/class.md +++ b/guide/src/class.md @@ -59,7 +59,7 @@ impl MyClass { #[new] fn __new__(obj: &PyRawObject, num: i32) -> PyResult<()> { - obj.init(|_| { + obj.init(|| { MyClass { num, } @@ -95,14 +95,13 @@ with value of custom class struct. Subclass must call parent's `__new__` method. #[pyclass] struct BaseClass { val1: usize, - token: PyToken, } #[pymethods] impl BaseClass { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|token| BaseClass{val1: 10, token}) + obj.init(|| BaseClass{ val1: 10 }) } pub fn method(&self) -> PyResult<()> { @@ -113,14 +112,13 @@ impl BaseClass { #[pyclass(extends=BaseClass)] struct SubClass { val2: usize, - token: PyToken, } #[pymethods] impl SubClass { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|token| SubClass{val2: 10, token}); + obj.init(|| SubClass{ val2: 10 }); BaseClass::__new__(obj) } @@ -513,7 +511,6 @@ use pyo3::prelude::*; #[pyclass] struct ClassWithGCSupport { obj: Option, - token: PyToken, } #[pyproto] @@ -562,7 +559,6 @@ use pyo3::prelude::*; #[pyclass] struct MyIterator { iter: Box + Send>, - token: PyToken, } #[pyproto] diff --git a/guide/src/rust-cpython.md b/guide/src/rust-cpython.md index 7bba1dc1..92324005 100644 --- a/guide/src/rust-cpython.md +++ b/guide/src/rust-cpython.md @@ -41,7 +41,7 @@ struct MyClass { impl MyClass { #[new] fn __new__(obj: &PyRawObject, num: u32) -> PyResult<()> { - obj.init(|token| { + obj.init(|| { MyClass { num, } diff --git a/pyo3-derive-backend/src/module.rs b/pyo3-derive-backend/src/module.rs index e6a08332..53965382 100644 --- a/pyo3-derive-backend/src/module.rs +++ b/pyo3-derive-backend/src/module.rs @@ -86,8 +86,8 @@ fn wrap_fn_argument<'a>(input: &'a syn::FnArg, name: &'a syn::Ident) -> Option) -> TokenStream { let (params, flags, base) = parse_attribute(attr); let doc = utils::get_doc(&class.attrs, true); - let mut token: Option = None; let mut descriptors = Vec::new(); if let syn::Fields::Named(ref mut fields) = class.fields { for field in fields.named.iter_mut() { - if is_python_token(field) { - if token.is_none() { - token = field.ident.clone(); - } else { - panic!("You can only have one PyToken per class"); - } - } else { - let field_descs = parse_descriptors(field); - if !field_descs.is_empty() { - descriptors.push((field.clone(), field_descs)); - } + let field_descs = parse_descriptors(field); + if !field_descs.is_empty() { + descriptors.push((field.clone(), field_descs)); } } } else { panic!("#[pyclass] can only be used with C-style structs") } - impl_class(&class.ident, &base, token, doc, params, flags, descriptors) + impl_class(&class.ident, &base, doc, params, flags, descriptors) } fn parse_descriptors(item: &mut syn::Field) -> Vec { @@ -72,7 +63,6 @@ fn parse_descriptors(item: &mut syn::Field) -> Vec { fn impl_class( cls: &syn::Ident, base: &syn::TypePath, - token: Option, doc: syn::Lit, params: HashMap<&'static str, syn::Expr>, flags: Vec, @@ -83,38 +73,6 @@ fn impl_class( None => quote! { #cls }.to_string(), }; - let extra = if let Some(token) = token { - Some(quote! { - impl ::pyo3::PyObjectWithToken for #cls { - fn py<'p>(&'p self) -> ::pyo3::Python<'p> { - self.#token.py() - } - } - impl<'a> ::std::convert::From<&'a mut #cls> for &'a #cls - { - fn from(ob: &'a mut #cls) -> Self { - unsafe{std::mem::transmute(ob)} - } - } - impl ::std::fmt::Debug for #cls { - fn fmt(&self, f : &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { - use ::pyo3::ObjectProtocol; - let s = self.repr().map_err(|_| ::std::fmt::Error)?; - f.write_str(&s.to_string_lossy()) - } - } - impl ::std::fmt::Display for #cls { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { - use ::pyo3::ObjectProtocol; - let s = self.str().map_err(|_| ::std::fmt::Error)?; - f.write_str(&s.to_string_lossy()) - } - } - }) - } else { - None - }; - let extra = { if let Some(freelist) = params.get("freelist") { Some(quote! { @@ -133,11 +91,9 @@ fn impl_class( } } } - - #extra }) } else { - extra + None } }; @@ -209,7 +165,7 @@ fn impl_class( // objects, so for now I'm keeping it impl ::pyo3::IntoPyObject for #cls { fn into_object(self, py: ::pyo3::Python) -> ::pyo3::PyObject { - ::pyo3::Py::new(py, |_| self).unwrap().into_object(py) + ::pyo3::Py::new(py, || self).unwrap().into_object(py) } } @@ -337,18 +293,6 @@ fn impl_descriptors(cls: &syn::Type, descriptors: Vec<(syn::Field, Vec)> } } -fn is_python_token(field: &syn::Field) -> bool { - match field.ty { - syn::Type::Path(ref typath) => { - if let Some(segment) = typath.path.segments.last() { - return segment.value().ident.to_string() == "PyToken"; - } - } - _ => (), - } - return false; -} - fn parse_attribute( args: &Vec, ) -> ( diff --git a/src/instance.rs b/src/instance.rs index 0da4fd8a..d97e0aec 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -1,9 +1,7 @@ // Copyright (c) 2017-present PyO3 Project and Contributors use std; -use std::marker::PhantomData; use std::ptr::NonNull; -use std::rc::Rc; use crate::conversion::{FromPyObject, IntoPyObject, ToPyObject}; use crate::err::{PyErr, PyResult}; @@ -17,26 +15,16 @@ use crate::typeob::PyTypeCreate; use crate::typeob::{PyTypeInfo, PyTypeObject}; use crate::types::PyObjectRef; -pub struct PyToken(PhantomData>); - -impl PyToken { - pub(crate) fn new() -> PyToken { - PyToken(PhantomData) - } - - #[inline] - pub fn py(&self) -> Python { - unsafe { Python::assume_gil_acquired() } - } -} - /// Any instance that is managed Python can have access to `gil`. -pub trait PyObjectWithToken: Sized { +/// +/// Originally, this was given to all classes with a `PyToken` field, but since `PyToken` was +/// removed this is only given to native types. +pub trait PyObjectWithGIL: Sized { fn py(&self) -> Python; } #[doc(hidden)] -pub trait PyNativeType: PyObjectWithToken {} +pub trait PyNativeType: PyObjectWithGIL {} /// Trait implements object reference extraction from python managed pointer. pub trait AsPyRef: Sized { @@ -174,7 +162,7 @@ where /// Returns `Py`. pub fn new(py: Python, f: F) -> PyResult> where - F: FnOnce(crate::PyToken) -> T, + F: FnOnce() -> T, T: PyTypeObject + PyTypeInfo, { let ob = ::create(py)?; @@ -188,7 +176,7 @@ where /// Returns references to `T` pub fn new_ref(py: Python, f: F) -> PyResult<&T> where - F: FnOnce(crate::PyToken) -> T, + F: FnOnce() -> T, T: PyTypeObject + PyTypeInfo, { let ob = ::create(py)?; @@ -201,7 +189,7 @@ where /// Returns mutable references to `T` pub fn new_mut(py: Python, f: F) -> PyResult<&mut T> where - F: FnOnce(crate::PyToken) -> T, + F: FnOnce() -> T, T: PyTypeObject + PyTypeInfo, { let ob = ::create(py)?; diff --git a/src/lib.rs b/src/lib.rs index 5841450b..792ecc2c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,7 +143,7 @@ pub use crate::conversion::{ ToBorrowedObject, ToPyObject, }; pub use crate::err::{PyDowncastError, PyErr, PyErrArguments, PyErrValue, PyResult}; -pub use crate::instance::{AsPyRef, Py, PyNativeType, PyObjectWithToken, PyToken}; +pub use crate::instance::{AsPyRef, Py, PyNativeType, PyObjectWithGIL}; pub use crate::noargs::NoArgs; pub use crate::object::PyObject; pub use crate::objectprotocol::ObjectProtocol; diff --git a/src/object.rs b/src/object.rs index 694a7f93..984f325e 100644 --- a/src/object.rs +++ b/src/object.rs @@ -8,7 +8,7 @@ use crate::conversion::{ }; use crate::err::{PyDowncastError, PyErr, PyResult}; use crate::ffi; -use crate::instance::{AsPyRef, PyObjectWithToken}; +use crate::instance::{AsPyRef, PyObjectWithGIL}; use crate::python::{IntoPyPointer, NonNullPyObject, Python, ToPyPointer}; use crate::pythonrun; use crate::types::{PyDict, PyObjectRef, PyTuple}; diff --git a/src/objectprotocol.rs b/src/objectprotocol.rs index c249f1f6..17ad6119 100644 --- a/src/objectprotocol.rs +++ b/src/objectprotocol.rs @@ -3,7 +3,7 @@ use crate::conversion::{FromPyObject, IntoPyTuple, PyTryFrom, ToBorrowedObject, ToPyObject}; use crate::err::{self, PyDowncastError, PyErr, PyResult}; use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{IntoPyPointer, Python, ToPyPointer}; use crate::typeob::PyTypeInfo; @@ -207,7 +207,7 @@ pub trait ObjectProtocol { impl ObjectProtocol for T where - T: PyObjectWithToken + ToPyPointer, + T: PyObjectWithGIL + ToPyPointer, { fn hasattr(&self, attr_name: N) -> PyResult where diff --git a/src/prelude.rs b/src/prelude.rs index 288611b6..24fff0e0 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -12,7 +12,7 @@ pub use crate::conversion::{FromPyObject, IntoPyObject, PyTryFrom, PyTryInto, ToPyObject}; pub use crate::err::{PyErr, PyResult}; -pub use crate::instance::{AsPyRef, Py, PyToken}; +pub use crate::instance::{AsPyRef, Py}; pub use crate::noargs::NoArgs; pub use crate::object::PyObject; pub use crate::objectprotocol::ObjectProtocol; diff --git a/src/python.rs b/src/python.rs index 6fca9706..1aa2f9e0 100644 --- a/src/python.rs +++ b/src/python.rs @@ -5,7 +5,7 @@ use crate::conversion::PyTryFrom; use crate::err::{PyDowncastError, PyErr, PyResult}; use crate::ffi; -use crate::instance::{AsPyRef, Py, PyToken}; +use crate::instance::{AsPyRef, Py}; use crate::object::PyObject; use crate::pythonrun::{self, GILGuard}; use crate::typeob::PyTypeCreate; @@ -256,7 +256,7 @@ impl<'p> Python<'p> { #[inline] pub fn init(self, f: F) -> PyResult> where - F: FnOnce(PyToken) -> T, + F: FnOnce() -> T, T: PyTypeCreate, { Py::new(self, f) @@ -267,7 +267,7 @@ impl<'p> Python<'p> { #[inline] pub fn init_ref(self, f: F) -> PyResult<&'p T> where - F: FnOnce(PyToken) -> T, + F: FnOnce() -> T, T: PyTypeCreate, { Py::new_ref(self, f) @@ -278,7 +278,7 @@ impl<'p> Python<'p> { #[inline] pub fn init_mut(self, f: F) -> PyResult<&'p mut T> where - F: FnOnce(PyToken) -> T, + F: FnOnce() -> T, T: PyTypeCreate, { Py::new_mut(self, f) diff --git a/src/typeob.rs b/src/typeob.rs index 23f059a4..342bfbbd 100644 --- a/src/typeob.rs +++ b/src/typeob.rs @@ -8,14 +8,14 @@ use std::ffi::CString; use std::mem; use std::os::raw::c_void; -use crate::{class, ffi, pythonrun}; use crate::class::methods::PyMethodDefType; use crate::err::{PyErr, PyResult}; -use crate::instance::{Py, PyObjectWithToken, PyToken}; -use crate::python::{IntoPyPointer, Python}; +use crate::instance::{Py, PyObjectWithGIL}; use crate::python::ToPyPointer; +use crate::python::{IntoPyPointer, Python}; use crate::types::PyObjectRef; use crate::types::PyType; +use crate::{class, ffi, pythonrun}; /// Python type information. pub trait PyTypeInfo { @@ -79,15 +79,13 @@ pub const PY_TYPE_FLAG_DICT: usize = 1 << 3; /// use pyo3::prelude::*; /// /// #[pyclass] -/// struct MyClass { -/// token: PyToken -/// } +/// struct MyClass { } /// /// #[pymethods] /// impl MyClass { /// #[new] /// fn __new__(obj: &PyRawObject) -> PyResult<()> { -/// obj.init(|token| MyClass { token }) +/// obj.init(|| MyClass { }) /// } /// } /// ``` @@ -144,11 +142,11 @@ impl PyRawObject { } pub fn init(&self, f: F) -> PyResult<()> - where - F: FnOnce(PyToken) -> T, - T: PyTypeInfo, + where + F: FnOnce() -> T, + T: PyTypeInfo, { - let value = f(PyToken::new()); + let value = f(); unsafe { let ptr = (self.ptr as *mut u8).offset(T::OFFSET) as *mut T; @@ -181,7 +179,7 @@ impl IntoPyPointer for PyRawObject { } } -impl PyObjectWithToken for PyRawObject { +impl PyObjectWithGIL for PyRawObject { #[inline] fn py(&self) -> Python { unsafe { Python::assume_gil_acquired() } @@ -210,7 +208,9 @@ pub trait PyObjectAlloc: PyTypeInfo { unsafe fn drop(_py: Python, _obj: *mut ffi::PyObject) {} } -impl PyObjectAlloc for T where T: PyTypeInfo +impl PyObjectAlloc for T +where + T: PyTypeInfo, { #[allow(unconditional_recursion)] /// Calls the rust destructor for the object. @@ -233,11 +233,11 @@ impl PyObjectAlloc for T where T: PyTypeInfo Self::drop(py, obj); #[cfg(Py_3)] - { - if ffi::PyObject_CallFinalizerFromDealloc(obj) < 0 { - return; - } + { + if ffi::PyObject_CallFinalizerFromDealloc(obj) < 0 { + return; } + } match Self::type_object().tp_free { Some(free) => free(obj as *mut c_void), @@ -312,8 +312,8 @@ pub trait PyTypeCreate: PyObjectAlloc + PyTypeInfo + Sized { impl PyTypeCreate for T where T: PyObjectAlloc + PyTypeInfo + Sized {} impl PyTypeObject for T - where - T: PyTypeCreate, +where + T: PyTypeCreate, { fn init_type() { ::init_type() @@ -327,8 +327,8 @@ impl PyTypeObject for T /// Register new type in python object system. #[cfg(not(Py_LIMITED_API))] pub fn initialize_type(py: Python, module_name: Option<&str>) -> PyResult<()> - where - T: PyObjectAlloc + PyTypeInfo, +where + T: PyObjectAlloc + PyTypeInfo, { // type name let name = match module_name { @@ -465,8 +465,8 @@ fn async_methods(type_info: &mut ffi::PyTypeObject) { fn async_methods(_type_info: &mut ffi::PyTypeObject) {} unsafe extern "C" fn tp_dealloc_callback(obj: *mut ffi::PyObject) - where - T: PyObjectAlloc, +where + T: PyObjectAlloc, { let _pool = pythonrun::GILPool::new_no_pointers(); let py = Python::assume_gil_acquired(); @@ -478,9 +478,9 @@ fn py_class_flags(type_object: &mut ffi::PyTypeObject) { if type_object.tp_traverse != None || type_object.tp_clear != None || T::FLAGS & PY_TYPE_FLAG_GC != 0 - { - type_object.tp_flags = ffi::Py_TPFLAGS_DEFAULT | ffi::Py_TPFLAGS_HAVE_GC; - } else { + { + type_object.tp_flags = ffi::Py_TPFLAGS_DEFAULT | ffi::Py_TPFLAGS_HAVE_GC; + } else { type_object.tp_flags = ffi::Py_TPFLAGS_DEFAULT; } if T::FLAGS & PY_TYPE_FLAG_BASETYPE != 0 { @@ -493,10 +493,10 @@ fn py_class_flags(type_object: &mut ffi::PyTypeObject) { if type_object.tp_traverse != None || type_object.tp_clear != None || T::FLAGS & PY_TYPE_FLAG_GC != 0 - { - type_object.tp_flags = - ffi::Py_TPFLAGS_DEFAULT | ffi::Py_TPFLAGS_CHECKTYPES | ffi::Py_TPFLAGS_HAVE_GC; - } else { + { + type_object.tp_flags = + ffi::Py_TPFLAGS_DEFAULT | ffi::Py_TPFLAGS_CHECKTYPES | ffi::Py_TPFLAGS_HAVE_GC; + } else { type_object.tp_flags = ffi::Py_TPFLAGS_DEFAULT | ffi::Py_TPFLAGS_CHECKTYPES; } if !type_object.tp_as_buffer.is_null() { @@ -585,27 +585,27 @@ fn py_class_properties() -> Vec { for def in ::py_methods() .iter() .chain(::py_methods().iter()) - { - match *def { - PyMethodDefType::Getter(ref getter) => { - let name = getter.name.to_string(); - if !defs.contains_key(&name) { - let _ = defs.insert(name.clone(), ffi::PyGetSetDef_INIT); - } - let def = defs.get_mut(&name).expect("Failed to call get_mut"); - getter.copy_to(def); + { + match *def { + PyMethodDefType::Getter(ref getter) => { + let name = getter.name.to_string(); + if !defs.contains_key(&name) { + let _ = defs.insert(name.clone(), ffi::PyGetSetDef_INIT); } - PyMethodDefType::Setter(ref setter) => { - let name = setter.name.to_string(); - if !defs.contains_key(&name) { - let _ = defs.insert(name.clone(), ffi::PyGetSetDef_INIT); - } - let def = defs.get_mut(&name).expect("Failed to call get_mut"); - setter.copy_to(def); - } - _ => (), + let def = defs.get_mut(&name).expect("Failed to call get_mut"); + getter.copy_to(def); } + PyMethodDefType::Setter(ref setter) => { + let name = setter.name.to_string(); + if !defs.contains_key(&name) { + let _ = defs.insert(name.clone(), ffi::PyGetSetDef_INIT); + } + let def = defs.get_mut(&name).expect("Failed to call get_mut"); + setter.copy_to(def); + } + _ => (), } + } defs.values().cloned().collect() } diff --git a/src/types/bytearray.rs b/src/types/bytearray.rs index bf6da490..4fe1280f 100644 --- a/src/types/bytearray.rs +++ b/src/types/bytearray.rs @@ -2,7 +2,7 @@ use crate::err::{PyErr, PyResult}; use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; use std::os::raw::c_char; diff --git a/src/types/complex.rs b/src/types/complex.rs index b6d68ec6..030486be 100644 --- a/src/types/complex.rs +++ b/src/types/complex.rs @@ -1,5 +1,5 @@ use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; #[cfg(any(not(Py_LIMITED_API), not(Py_3)))] diff --git a/src/types/dict.rs b/src/types/dict.rs index 887e382d..00da0bdf 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -3,7 +3,7 @@ use crate::conversion::{IntoPyObject, ToBorrowedObject, ToPyObject}; use crate::err::{self, PyErr, PyResult}; use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{IntoPyPointer, Python, ToPyPointer}; use crate::types::{PyList, PyObjectRef}; diff --git a/src/types/floatob.rs b/src/types/floatob.rs index 28cc2d91..c1cc501e 100644 --- a/src/types/floatob.rs +++ b/src/types/floatob.rs @@ -5,7 +5,7 @@ use crate::conversion::{IntoPyObject, ToPyObject}; use crate::err::PyErr; use crate::ffi; -use crate::instance::{Py, PyObjectWithToken}; +use crate::instance::{Py, PyObjectWithGIL}; use crate::object::PyObject; use crate::objectprotocol::ObjectProtocol; use crate::python::{Python, ToPyPointer}; diff --git a/src/types/iterator.rs b/src/types/iterator.rs index 6058ca32..3f500a1a 100644 --- a/src/types/iterator.rs +++ b/src/types/iterator.rs @@ -4,7 +4,7 @@ use crate::err::{PyDowncastError, PyErr, PyResult}; use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::python::{Python, ToPyPointer}; use crate::types::PyObjectRef; diff --git a/src/types/list.rs b/src/types/list.rs index 0f6fbb94..44c32257 100644 --- a/src/types/list.rs +++ b/src/types/list.rs @@ -7,7 +7,7 @@ use std; use crate::conversion::{IntoPyObject, ToBorrowedObject, ToPyObject}; use crate::err::{self, PyResult}; use crate::ffi::{self, Py_ssize_t}; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{IntoPyPointer, Python, ToPyPointer}; use crate::types::PyObjectRef; diff --git a/src/types/mod.rs b/src/types/mod.rs index a92db71b..eb50534a 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -66,7 +66,7 @@ macro_rules! pyobject_native_type_named ( } } - impl<$($type_param,)*> $crate::PyObjectWithToken for $name { + impl<$($type_param,)*> $crate::PyObjectWithGIL for $name { #[inline] fn py(&self) -> $crate::Python { unsafe { $crate::Python::assume_gil_acquired() } diff --git a/src/types/module.rs b/src/types/module.rs index 64f5ed5b..d20836c6 100644 --- a/src/types/module.rs +++ b/src/types/module.rs @@ -5,7 +5,7 @@ use crate::conversion::{IntoPyTuple, ToPyObject}; use crate::err::{PyErr, PyResult}; use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::objectprotocol::ObjectProtocol; use crate::python::{Python, ToPyPointer}; diff --git a/src/types/num2.rs b/src/types/num2.rs index 4e4bc280..322b2c26 100644 --- a/src/types/num2.rs +++ b/src/types/num2.rs @@ -11,7 +11,7 @@ use super::num_common::{err_if_invalid_value, IS_LITTLE_ENDIAN}; use conversion::{FromPyObject, IntoPyObject, ToPyObject}; use err::{PyErr, PyResult}; use ffi; -use instance::{Py, PyObjectWithToken}; +use instance::{Py, PyObjectWithGIL}; use object::PyObject; use python::{IntoPyPointer, Python, ToPyPointer}; use types::{exceptions, PyObjectRef}; diff --git a/src/types/num3.rs b/src/types/num3.rs index 9cc4652c..4e158ebc 100644 --- a/src/types/num3.rs +++ b/src/types/num3.rs @@ -9,7 +9,7 @@ use super::num_common::{err_if_invalid_value, IS_LITTLE_ENDIAN}; use crate::conversion::{FromPyObject, IntoPyObject, ToPyObject}; use crate::err::{PyErr, PyResult}; use crate::ffi; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; use crate::types::{exceptions, PyObjectRef}; diff --git a/src/types/sequence.rs b/src/types/sequence.rs index 8dea3058..64df512e 100644 --- a/src/types/sequence.rs +++ b/src/types/sequence.rs @@ -4,7 +4,7 @@ use crate::buffer; use crate::conversion::{FromPyObject, PyTryFrom, ToBorrowedObject}; use crate::err::{self, PyDowncastError, PyErr, PyResult}; use crate::ffi::{self, Py_ssize_t}; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::objectprotocol::ObjectProtocol; use crate::python::ToPyPointer; diff --git a/src/types/set.rs b/src/types/set.rs index 59c0141b..899e963c 100644 --- a/src/types/set.rs +++ b/src/types/set.rs @@ -4,7 +4,7 @@ use crate::conversion::{ToBorrowedObject, ToPyObject}; use crate::err::{self, PyErr, PyResult}; use crate::ffi; -use crate::instance::{AsPyRef, Py, PyObjectWithToken}; +use crate::instance::{AsPyRef, Py, PyObjectWithGIL}; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; use std::{collections, hash}; diff --git a/src/types/slice.rs b/src/types/slice.rs index 3ed5d557..b7cfc576 100644 --- a/src/types/slice.rs +++ b/src/types/slice.rs @@ -5,7 +5,7 @@ use std::os::raw::c_long; use crate::conversion::ToPyObject; use crate::err::{PyErr, PyResult}; use crate::ffi::{self, Py_ssize_t}; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; diff --git a/src/types/string.rs b/src/types/string.rs index ccc5823d..78473ce6 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -7,7 +7,7 @@ use std::{mem, str}; use crate::err::{PyErr, PyResult}; use crate::ffi; -use crate::instance::{Py, PyObjectWithToken}; +use crate::instance::{Py, PyObjectWithGIL}; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; use crate::types::exceptions; diff --git a/src/types/string2.rs b/src/types/string2.rs index 34e84567..6441f87c 100644 --- a/src/types/string2.rs +++ b/src/types/string2.rs @@ -10,7 +10,7 @@ use std::str; use super::PyObjectRef; use err::{PyErr, PyResult}; use ffi; -use instance::{Py, PyObjectWithToken}; +use instance::{Py, PyObjectWithGIL}; use object::PyObject; use objectprotocol::ObjectProtocol; use python::{Python, ToPyPointer}; diff --git a/src/types/stringutils.rs b/src/types/stringutils.rs index 4a672626..0f3ce9af 100644 --- a/src/types/stringutils.rs +++ b/src/types/stringutils.rs @@ -1,6 +1,6 @@ use crate::conversion::{IntoPyObject, PyTryFrom, ToPyObject}; use crate::err::PyResult; -use crate::instance::PyObjectWithToken; +use crate::instance::PyObjectWithGIL; use crate::object::PyObject; use crate::python::Python; use crate::types::{PyObjectRef, PyString}; diff --git a/src/types/tuple.rs b/src/types/tuple.rs index e1a1da74..574d5379 100644 --- a/src/types/tuple.rs +++ b/src/types/tuple.rs @@ -4,7 +4,7 @@ use super::exceptions; use crate::conversion::{FromPyObject, IntoPyObject, IntoPyTuple, PyTryFrom, ToPyObject}; use crate::err::{PyErr, PyResult}; use crate::ffi::{self, Py_ssize_t}; -use crate::instance::{AsPyRef, Py, PyObjectWithToken}; +use crate::instance::{AsPyRef, Py, PyObjectWithGIL}; use crate::object::PyObject; use crate::python::{IntoPyPointer, Python, ToPyPointer}; use crate::types::PyObjectRef; diff --git a/src/types/typeobject.rs b/src/types/typeobject.rs index 99505d2e..81a30598 100644 --- a/src/types/typeobject.rs +++ b/src/types/typeobject.rs @@ -7,7 +7,7 @@ use std::ffi::CStr; use crate::err::{PyErr, PyResult}; use crate::ffi; -use crate::instance::{Py, PyObjectWithToken}; +use crate::instance::{Py, PyObjectWithGIL}; use crate::object::PyObject; use crate::python::{Python, ToPyPointer}; use crate::typeob::{PyTypeInfo, PyTypeObject}; diff --git a/tests/test_arithmetics.rs b/tests/test_arithmetics.rs index c59f5f7c..aa7bc3ab 100644 --- a/tests/test_arithmetics.rs +++ b/tests/test_arithmetics.rs @@ -5,7 +5,6 @@ extern crate pyo3; use pyo3::class::*; use pyo3::prelude::*; use pyo3::types::PyObjectRef; -use pyo3::PyObjectWithToken; #[macro_use] mod common; @@ -37,7 +36,7 @@ fn unary_arithmetic() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|_| UnaryArithmetic {}).unwrap(); + let c = py.init(|| UnaryArithmetic {}).unwrap(); py_run!(py, c, "assert -c == 'neg'"); py_run!(py, c, "assert +c == 'pos'"); py_run!(py, c, "assert abs(c) == 'abs'"); @@ -115,7 +114,7 @@ fn inplace_operations() { let py = gil.python(); let init = |value, code| { - let c = py.init(|_| InPlaceOperations { value }).unwrap(); + let c = py.init(|| InPlaceOperations { value }).unwrap(); py_run!(py, c, code); }; @@ -169,7 +168,7 @@ fn binary_arithmetic() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|_| BinaryArithmetic {}).unwrap(); + let c = py.init(|| BinaryArithmetic {}).unwrap(); py_run!(py, c, "assert c + c == 'BA + BA'"); py_run!(py, c, "assert c + 1 == 'BA + 1'"); py_run!(py, c, "assert 1 + c == '1 + BA'"); @@ -212,9 +211,7 @@ impl PyObjectProtocol for RichComparisons { } #[pyclass] -struct RichComparisons2 { - py: PyToken, -} +struct RichComparisons2 {} #[pyproto] impl PyObjectProtocol for RichComparisons2 { @@ -223,10 +220,11 @@ impl PyObjectProtocol for RichComparisons2 { } fn __richcmp__(&self, _other: &PyObjectRef, op: CompareOp) -> PyResult { + let gil = GILGuard::acquire(); match op { - CompareOp::Eq => Ok(true.to_object(self.py())), - CompareOp::Ne => Ok(false.to_object(self.py())), - _ => Ok(self.py().NotImplemented()), + CompareOp::Eq => Ok(true.to_object(gil.python())), + CompareOp::Ne => Ok(false.to_object(gil.python())), + _ => Ok(gil.python().NotImplemented()), } } } @@ -236,7 +234,7 @@ fn rich_comparisons() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|_| RichComparisons {}).unwrap(); + let c = py.init(|| 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'"); @@ -263,7 +261,7 @@ fn rich_comparisons_python_3_type_error() { let gil = Python::acquire_gil(); let py = gil.python(); - let c2 = py.init(|t| RichComparisons2 { py: t }).unwrap(); + let c2 = py.init(|| RichComparisons2 {}).unwrap(); py_expect_exception!(py, c2, "c2 < c2", TypeError); py_expect_exception!(py, c2, "c2 < 1", TypeError); py_expect_exception!(py, c2, "1 < c2", TypeError); diff --git a/tests/test_buffer_protocol.rs b/tests/test_buffer_protocol.rs index 2c384094..fe844233 100644 --- a/tests/test_buffer_protocol.rs +++ b/tests/test_buffer_protocol.rs @@ -14,7 +14,6 @@ use pyo3::types::PyDict; #[pyclass] struct TestClass { vec: Vec, - token: PyToken, } #[pyproto] @@ -72,9 +71,8 @@ fn test_buffer() { let py = gil.python(); let t = py - .init(|t| TestClass { + .init(|| TestClass { vec: vec![b' ', b'2', b'3'], - token: t, }) .unwrap(); @@ -90,9 +88,8 @@ fn test_buffer() { let py = gil.python(); let t = py - .init(|t| TestClass { + .init(|| TestClass { vec: vec![b' ', b'2', b'3'], - token: t, }) .unwrap(); diff --git a/tests/test_class_new.rs b/tests/test_class_new.rs index 6ecba7ea..7f58a8c2 100644 --- a/tests/test_class_new.rs +++ b/tests/test_class_new.rs @@ -12,7 +12,7 @@ struct EmptyClassWithNew {} impl EmptyClassWithNew { #[__new__] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| EmptyClassWithNew {}) + obj.init(|| EmptyClassWithNew {}) } } @@ -37,7 +37,7 @@ struct NewWithOneArg { impl NewWithOneArg { #[new] fn __new__(obj: &PyRawObject, arg: i32) -> PyResult<()> { - obj.init(|_| NewWithOneArg { _data: arg }) + obj.init(|| NewWithOneArg { _data: arg }) } } @@ -61,7 +61,7 @@ struct NewWithTwoArgs { impl NewWithTwoArgs { #[new] fn __new__(obj: &PyRawObject, arg1: i32, arg2: i32) -> PyResult<()> { - obj.init(|_| NewWithTwoArgs { + obj.init(|| NewWithTwoArgs { _data1: arg1, _data2: arg2, }) diff --git a/tests/test_dunder.rs b/tests/test_dunder.rs index 9582bbea..d1fa1dc6 100644 --- a/tests/test_dunder.rs +++ b/tests/test_dunder.rs @@ -2,6 +2,8 @@ extern crate pyo3; +use std::{isize, iter}; + use pyo3::class::{ PyContextProtocol, PyIterProtocol, PyMappingProtocol, PyObjectProtocol, PySequenceProtocol, }; @@ -10,8 +12,6 @@ use pyo3::ffi; use pyo3::prelude::*; use pyo3::python::ToPyPointer; use pyo3::types::{PyBytes, PyDict, PyObjectRef, PySlice, PyString, PyType}; -use pyo3::PyObjectWithToken; -use std::{isize, iter}; #[macro_use] mod common; @@ -19,7 +19,6 @@ mod common; #[pyclass] pub struct Len { l: usize, - token: PyToken, } #[pyproto] @@ -34,16 +33,15 @@ fn len() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new(py, |t| Len { l: 10, token: t }).unwrap(); + let inst = Py::new(py, || Len { l: 10 }).unwrap(); py_assert!(py, inst, "len(inst) == 10"); unsafe { assert_eq!(ffi::PyObject_Size(inst.as_ptr()), 10); assert_eq!(ffi::PyMapping_Size(inst.as_ptr()), 10); } - let inst = Py::new(py, |t| Len { + let inst = Py::new(py, || Len { l: (isize::MAX as usize) + 1, - token: t, }) .unwrap(); py_expect_exception!(py, inst, "len(inst)", OverflowError); @@ -52,7 +50,6 @@ fn len() { #[pyclass] struct Iterator { iter: Box + Send>, - token: PyToken, } #[pyproto] @@ -71,9 +68,8 @@ fn iterator() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new(py, |t| Iterator { + let inst = Py::new(py, || Iterator { iter: Box::new(5..8), - token: t, }) .unwrap(); py_assert!(py, inst, "iter(inst) is inst"); @@ -81,9 +77,7 @@ fn iterator() { } #[pyclass] -struct StringMethods { - token: PyToken, -} +struct StringMethods {} #[pyproto] impl<'p> PyObjectProtocol<'p> for StringMethods { @@ -100,11 +94,13 @@ impl<'p> PyObjectProtocol<'p> for StringMethods { } fn __bytes__(&self) -> PyResult { - Ok(PyBytes::new(self.py(), b"bytes").into()) + let gil = GILGuard::acquire(); + Ok(PyBytes::new(gil.python(), b"bytes").into()) } fn __unicode__(&self) -> PyResult { - Ok(PyString::new(self.py(), "unicode").into()) + let gil = GILGuard::acquire(); + Ok(PyString::new(gil.python(), "unicode").into()) } } @@ -114,7 +110,7 @@ fn string_methods() { let gil = Python::acquire_gil(); let py = gil.python(); - let obj = Py::new(py, |t| StringMethods { token: t }).unwrap(); + let obj = Py::new(py, || StringMethods {}).unwrap(); py_assert!(py, obj, "str(obj) == 'str'"); py_assert!(py, obj, "repr(obj) == 'repr'"); py_assert!(py, obj, "'{0:x}'.format(obj) == 'format(x)'"); @@ -127,7 +123,7 @@ fn string_methods() { let gil = Python::acquire_gil(); let py = gil.python(); - let obj = Py::new(py, |t| StringMethods { token: t }).unwrap(); + let obj = Py::new(py, || StringMethods {}).unwrap(); py_assert!(py, obj, "str(obj) == 'str'"); py_assert!(py, obj, "repr(obj) == 'repr'"); py_assert!(py, obj, "unicode(obj) == 'unicode'"); @@ -137,7 +133,6 @@ fn string_methods() { #[pyclass] struct Comparisons { val: i32, - token: PyToken, } #[pyproto] @@ -155,10 +150,10 @@ fn comparisons() { let gil = Python::acquire_gil(); let py = gil.python(); - let zero = Py::new(py, |t| Comparisons { val: 0, token: t }).unwrap(); - let one = Py::new(py, |t| Comparisons { val: 1, token: t }).unwrap(); - let ten = Py::new(py, |t| Comparisons { val: 10, token: t }).unwrap(); - let minus_one = Py::new(py, |t| Comparisons { val: -1, token: t }).unwrap(); + let zero = Py::new(py, || Comparisons { val: 0 }).unwrap(); + let one = Py::new(py, || Comparisons { val: 1 }).unwrap(); + let ten = Py::new(py, || Comparisons { val: 10 }).unwrap(); + let minus_one = Py::new(py, || Comparisons { val: -1 }).unwrap(); py_assert!(py, one, "hash(one) == 1"); py_assert!(py, ten, "hash(ten) == 10"); py_assert!(py, minus_one, "hash(minus_one) == -2"); @@ -168,9 +163,7 @@ fn comparisons() { } #[pyclass] -struct Sequence { - token: PyToken, -} +struct Sequence {} #[pyproto] impl PySequenceProtocol for Sequence { @@ -191,15 +184,13 @@ fn sequence() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|t| Sequence { token: t }).unwrap(); + let c = py.init(|| Sequence {}).unwrap(); py_assert!(py, c, "list(c) == [0, 1, 2, 3, 4]"); py_expect_exception!(py, c, "c['abc']", TypeError); } #[pyclass] -struct Callable { - token: PyToken, -} +struct Callable {} #[pymethods] impl Callable { @@ -214,11 +205,11 @@ fn callable() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|t| Callable { token: t }).unwrap(); + let c = py.init(|| Callable {}).unwrap(); py_assert!(py, c, "callable(c)"); py_assert!(py, c, "c(7) == 42"); - let nc = py.init(|t| Comparisons { val: 0, token: t }).unwrap(); + let nc = py.init(|| Comparisons { val: 0 }).unwrap(); py_assert!(py, nc, "not callable(nc)"); } @@ -226,7 +217,6 @@ fn callable() { struct SetItem { key: i32, val: i32, - token: PyToken, } #[pyproto] @@ -243,13 +233,7 @@ fn setitem() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py - .init_ref(|t| SetItem { - key: 0, - val: 0, - token: t, - }) - .unwrap(); + let c = py.init_ref(|| SetItem { key: 0, val: 0 }).unwrap(); py_run!(py, c, "c[1] = 2"); assert_eq!(c.key, 1); assert_eq!(c.val, 2); @@ -259,7 +243,6 @@ fn setitem() { #[pyclass] struct DelItem { key: i32, - token: PyToken, } #[pyproto] @@ -275,7 +258,7 @@ fn delitem() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init_ref(|t| DelItem { key: 0, token: t }).unwrap(); + let c = py.init_ref(|| DelItem { key: 0 }).unwrap(); py_run!(py, c, "del c[1]"); assert_eq!(c.key, 1); py_expect_exception!(py, c, "c[1] = 2", NotImplementedError); @@ -284,7 +267,6 @@ fn delitem() { #[pyclass] struct SetDelItem { val: Option, - token: PyToken, } #[pyproto] @@ -305,12 +287,7 @@ fn setdelitem() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py - .init_ref(|t| SetDelItem { - val: None, - token: t, - }) - .unwrap(); + let c = py.init_ref(|| SetDelItem { val: None }).unwrap(); py_run!(py, c, "c[1] = 2"); assert_eq!(c.val, Some(2)); py_run!(py, c, "del c[1]"); @@ -318,9 +295,7 @@ fn setdelitem() { } #[pyclass] -struct Reversed { - token: PyToken, -} +struct Reversed {} #[pyproto] impl PyMappingProtocol for Reversed { @@ -334,14 +309,12 @@ fn reversed() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|t| Reversed { token: t }).unwrap(); + let c = py.init(|| Reversed {}).unwrap(); py_run!(py, c, "assert reversed(c) == 'I am reversed'"); } #[pyclass] -struct Contains { - token: PyToken, -} +struct Contains {} #[pyproto] impl PySequenceProtocol for Contains { @@ -355,7 +328,7 @@ fn contains() { let gil = Python::acquire_gil(); let py = gil.python(); - let c = py.init(|t| Contains { token: t }).unwrap(); + let c = py.init(|| Contains {}).unwrap(); py_run!(py, c, "assert 1 in c"); py_run!(py, c, "assert -1 not in c"); py_expect_exception!(py, c, "assert 'wrong type' not in c", TypeError); @@ -364,7 +337,6 @@ fn contains() { #[pyclass] struct ContextManager { exit_called: bool, - token: PyToken, } #[pyproto] @@ -379,8 +351,9 @@ impl<'p> PyContextProtocol<'p> for ContextManager { _value: Option<&'p PyObjectRef>, _traceback: Option<&'p PyObjectRef>, ) -> PyResult { + let gil = GILGuard::acquire(); self.exit_called = true; - if ty == Some(self.py().get_type::()) { + if ty == Some(gil.python().get_type::()) { Ok(true) } else { Ok(false) @@ -394,10 +367,7 @@ fn context_manager() { let py = gil.python(); let c = py - .init_mut(|t| ContextManager { - exit_called: false, - token: t, - }) + .init_mut(|| ContextManager { exit_called: false }) .unwrap(); py_run!(py, c, "with c as x: assert x == 42"); assert!(c.exit_called); @@ -430,21 +400,20 @@ fn test_basics() { } #[pyclass] -struct Test { - token: PyToken, -} +struct Test {} #[pyproto] impl<'p> PyMappingProtocol<'p> for Test { fn __getitem__(&self, idx: &PyObjectRef) -> PyResult { + let gil = GILGuard::acquire(); if let Ok(slice) = idx.cast_as::() { let indices = slice.indices(1000)?; if indices.start == 100 && indices.stop == 200 && indices.step == 1 { - return Ok("slice".into_object(self.py())); + return Ok("slice".into_object(gil.python())); } } else if let Ok(idx) = idx.extract::() { if idx == 1 { - return Ok("int".into_object(self.py())); + return Ok("int".into_object(gil.python())); } } Err(PyErr::new::("error")) @@ -456,7 +425,7 @@ fn test_cls_impl() { let gil = Python::acquire_gil(); let py = gil.python(); - let ob = py.init(|t| Test { token: t }).unwrap(); + let ob = py.init(|| Test {}).unwrap(); let d = PyDict::new(py); d.set_item("ob", ob).unwrap(); @@ -466,15 +435,13 @@ fn test_cls_impl() { } #[pyclass(dict)] -struct DunderDictSupport { - token: PyToken, -} +struct DunderDictSupport {} #[test] fn dunder_dict_support() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new_ref(py, |t| DunderDictSupport { token: t }).unwrap(); + let inst = Py::new_ref(py, || DunderDictSupport {}).unwrap(); py_run!( py, inst, @@ -486,15 +453,13 @@ fn dunder_dict_support() { } #[pyclass(weakref, dict)] -struct WeakRefDunderDictSupport { - token: PyToken, -} +struct WeakRefDunderDictSupport {} #[test] fn weakref_dunder_dict_support() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new_ref(py, |t| WeakRefDunderDictSupport { token: t }).unwrap(); + let inst = Py::new_ref(py, || WeakRefDunderDictSupport {}).unwrap(); py_run!( py, inst, diff --git a/tests/test_gc.rs b/tests/test_gc.rs index fbf4a533..acc020a2 100644 --- a/tests/test_gc.rs +++ b/tests/test_gc.rs @@ -2,6 +2,10 @@ extern crate pyo3; +use std::cell::RefCell; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + use pyo3::class::PyGCProtocol; use pyo3::class::PyTraverseError; use pyo3::class::PyVisit; @@ -10,19 +14,13 @@ use pyo3::prelude::*; use pyo3::python::ToPyPointer; use pyo3::types::PyObjectRef; use pyo3::types::PyTuple; -use pyo3::PyObjectWithToken; use pyo3::PyRawObject; -use std::cell::RefCell; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; #[macro_use] mod common; #[pyclass(freelist = 2)] -struct ClassWithFreelist { - token: PyToken, -} +struct ClassWithFreelist {} #[test] fn class_with_freelist() { @@ -31,8 +29,8 @@ fn class_with_freelist() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new(py, |t| ClassWithFreelist { token: t }).unwrap(); - let _inst2 = Py::new(py, |t| ClassWithFreelist { token: t }).unwrap(); + let inst = Py::new(py, || ClassWithFreelist {}).unwrap(); + let _inst2 = Py::new(py, || ClassWithFreelist {}).unwrap(); ptr = inst.as_ptr(); drop(inst); } @@ -41,10 +39,10 @@ fn class_with_freelist() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst3 = Py::new(py, |t| ClassWithFreelist { token: t }).unwrap(); + let inst3 = Py::new(py, || ClassWithFreelist {}).unwrap(); assert_eq!(ptr, inst3.as_ptr()); - let inst4 = Py::new(py, |t| ClassWithFreelist { token: t }).unwrap(); + let inst4 = Py::new(py, || ClassWithFreelist {}).unwrap(); assert_ne!(ptr, inst4.as_ptr()) } } @@ -64,7 +62,6 @@ impl Drop for TestDropCall { struct DataIsDropped { member1: TestDropCall, member2: TestDropCall, - token: PyToken, } #[test] @@ -76,14 +73,13 @@ fn data_is_dropped() { let gil = Python::acquire_gil(); let py = gil.python(); let inst = py - .init(|t| DataIsDropped { + .init(|| DataIsDropped { member1: TestDropCall { drop_called: Arc::clone(&drop_called1), }, member2: TestDropCall { drop_called: Arc::clone(&drop_called2), }, - token: t, }) .unwrap(); assert!(!drop_called1.load(Ordering::Relaxed)); @@ -96,9 +92,7 @@ fn data_is_dropped() { } #[pyclass] -struct ClassWithDrop { - token: PyToken, -} +struct ClassWithDrop {} impl Drop for ClassWithDrop { fn drop(&mut self) { @@ -125,7 +119,7 @@ fn create_pointers_in_drop() { let empty = PyTuple::empty(py); ptr = empty.as_ptr(); cnt = empty.get_refcnt() - 1; - let inst = py.init(|t| ClassWithDrop { token: t }).unwrap(); + let inst = py.init(|| ClassWithDrop {}).unwrap(); drop(inst); } @@ -147,7 +141,6 @@ fn create_pointers_in_drop() { struct GCIntegration { self_ref: RefCell, dropped: TestDropCall, - token: PyToken, } #[pyproto] @@ -157,7 +150,8 @@ impl PyGCProtocol for GCIntegration { } fn __clear__(&mut self) { - *self.self_ref.borrow_mut() = self.py().None(); + let gil = GILGuard::acquire(); + *self.self_ref.borrow_mut() = gil.python().None(); } } @@ -168,12 +162,11 @@ fn gc_integration() { { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new_ref(py, |t| GCIntegration { + let inst = Py::new_ref(py, || GCIntegration { self_ref: RefCell::new(py.None()), dropped: TestDropCall { drop_called: Arc::clone(&drop_called), }, - token: t, }) .unwrap(); @@ -187,28 +180,24 @@ fn gc_integration() { } #[pyclass(gc)] -struct GCIntegration2 { - token: PyToken, -} +struct GCIntegration2 {} #[test] fn gc_integration2() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new_ref(py, |t| GCIntegration2 { token: t }).unwrap(); + let inst = Py::new_ref(py, || GCIntegration2 {}).unwrap(); py_run!(py, inst, "import gc; assert inst in gc.get_objects()"); } #[pyclass(weakref)] -struct WeakRefSupport { - token: PyToken, -} +struct WeakRefSupport {} #[test] fn weakref_support() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = Py::new_ref(py, |t| WeakRefSupport { token: t }).unwrap(); + let inst = Py::new_ref(py, || WeakRefSupport {}).unwrap(); py_run!( py, inst, @@ -218,7 +207,6 @@ fn weakref_support() { #[pyclass] struct BaseClassWithDrop { - token: PyToken, data: Option>, } @@ -226,10 +214,7 @@ struct BaseClassWithDrop { impl BaseClassWithDrop { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|t| BaseClassWithDrop { - token: t, - data: None, - }) + obj.init(|| BaseClassWithDrop { data: None }) } } @@ -243,7 +228,6 @@ impl Drop for BaseClassWithDrop { #[pyclass(extends = BaseClassWithDrop)] struct SubClassWithDrop { - token: PyToken, data: Option>, } @@ -251,10 +235,7 @@ struct SubClassWithDrop { impl SubClassWithDrop { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|t| SubClassWithDrop { - token: t, - data: None, - })?; + obj.init(|| SubClassWithDrop { data: None })?; BaseClassWithDrop::__new__(obj) } } @@ -282,7 +263,8 @@ fn inheritance_with_new_methods_with_drop() { let obj = SubClassWithDrop::try_from_mut(inst).unwrap(); obj.data = Some(Arc::clone(&drop_called1)); - let base = obj.get_mut_base(); + let base: &mut ::BaseType = + unsafe { py.mut_from_borrowed_ptr(obj.as_ptr()) }; base.data = Some(Arc::clone(&drop_called2)); } diff --git a/tests/test_getter_setter.rs b/tests/test_getter_setter.rs index bf0b3474..8530fc7c 100644 --- a/tests/test_getter_setter.rs +++ b/tests/test_getter_setter.rs @@ -11,7 +11,6 @@ mod common; #[pyclass] struct ClassWithProperties { num: i32, - token: PyToken, } #[pymethods] @@ -36,9 +35,7 @@ fn class_with_properties() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = py - .init(|t| ClassWithProperties { num: 10, token: t }) - .unwrap(); + let inst = py.init(|| ClassWithProperties { num: 10 }).unwrap(); py_run!(py, inst, "assert inst.get_num() == 10"); py_run!(py, inst, "assert inst.get_num() == inst.DATA"); @@ -49,7 +46,6 @@ fn class_with_properties() { #[pyclass] struct GetterSetter { - token: PyToken, #[prop(get, set)] num: i32, #[prop(get, set)] @@ -69,9 +65,8 @@ fn getter_setter_autogen() { let py = gil.python(); let inst = py - .init(|t| GetterSetter { + .init(|| GetterSetter { num: 10, - token: t, text: "Hello".to_string(), }) .unwrap(); diff --git a/tests/test_inheritance.rs b/tests/test_inheritance.rs index fc27772a..6533fdbc 100644 --- a/tests/test_inheritance.rs +++ b/tests/test_inheritance.rs @@ -39,7 +39,7 @@ fn subclass() { impl BaseClass { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| BaseClass { val1: 10 }) + obj.init(|| BaseClass { val1: 10 }) } } @@ -53,7 +53,7 @@ struct SubClass { impl SubClass { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| SubClass { val2: 5 })?; + obj.init(|| SubClass { val2: 5 })?; BaseClass::__new__(obj) } } diff --git a/tests/test_methods.rs b/tests/test_methods.rs index b4bdea3f..a6e2fb39 100644 --- a/tests/test_methods.rs +++ b/tests/test_methods.rs @@ -4,7 +4,6 @@ extern crate pyo3; use pyo3::prelude::*; use pyo3::types::{PyDict, PyString, PyTuple, PyType}; -use pyo3::PyObjectWithToken; use pyo3::PyRawObject; #[macro_use] @@ -13,7 +12,6 @@ mod common; #[pyclass] struct InstanceMethod { member: i32, - token: PyToken, } #[pymethods] @@ -29,12 +27,7 @@ fn instance_method() { let gil = Python::acquire_gil(); let py = gil.python(); - let obj = py - .init_ref(|t| InstanceMethod { - member: 42, - token: t, - }) - .unwrap(); + let obj = py.init_ref(|| InstanceMethod { member: 42 }).unwrap(); assert_eq!(obj.method().unwrap(), 42); let d = PyDict::new(py); d.set_item("obj", obj).unwrap(); @@ -46,7 +39,6 @@ fn instance_method() { #[pyclass] struct InstanceMethodWithArgs { member: i32, - token: PyToken, } #[pymethods] @@ -63,12 +55,9 @@ fn instance_method_with_args() { let py = gil.python(); let obj = py - .init_ref(|t| InstanceMethodWithArgs { - member: 7, - token: t, - }) + .init_ref(|| InstanceMethodWithArgs { member: 7 }) .unwrap(); - assert!(obj.method(6).unwrap() == 42); + assert_eq!(obj.method(6).unwrap(), 42); let d = PyDict::new(py); d.set_item("obj", obj).unwrap(); py.run("assert obj.method(3) == 21", None, Some(d)).unwrap(); @@ -83,7 +72,7 @@ struct ClassMethod {} impl ClassMethod { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|_| ClassMethod {}) + obj.init(|| ClassMethod {}) } #[classmethod] @@ -114,9 +103,7 @@ fn class_method() { } #[pyclass] -struct ClassMethodWithArgs { - token: PyToken, -} +struct ClassMethodWithArgs {} #[pymethods] impl ClassMethodWithArgs { @@ -143,15 +130,13 @@ fn class_method_with_args() { } #[pyclass] -struct StaticMethod { - token: PyToken, -} +struct StaticMethod {} #[pymethods] impl StaticMethod { #[new] fn __new__(obj: &PyRawObject) -> PyResult<()> { - obj.init(|t| StaticMethod { token: t }) + obj.init(|| StaticMethod {}) } #[staticmethod] @@ -183,9 +168,7 @@ fn static_method() { } #[pyclass] -struct StaticMethodWithArgs { - token: PyToken, -} +struct StaticMethodWithArgs {} #[pymethods] impl StaticMethodWithArgs { @@ -210,9 +193,7 @@ fn static_method_with_args() { } #[pyclass] -struct MethArgs { - token: PyToken, -} +struct MethArgs {} #[pymethods] impl MethArgs { @@ -230,8 +211,13 @@ impl MethArgs { Ok(test) } #[args(args = "*", kwargs = "**")] - fn get_kwargs(&self, args: &PyTuple, kwargs: Option<&PyDict>) -> PyResult { - Ok([args.into(), kwargs.to_object(self.py())].to_object(self.py())) + fn get_kwargs( + &self, + py: Python, + args: &PyTuple, + kwargs: Option<&PyDict>, + ) -> PyResult { + Ok([args.into(), kwargs.to_object(py)].to_object(py)) } } @@ -239,7 +225,7 @@ impl MethArgs { fn meth_args() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst = py.init(|t| MethArgs { token: t }).unwrap(); + let inst = py.init(|| MethArgs {}).unwrap(); py_run!(py, inst, "assert inst.get_optional() == 10"); py_run!(py, inst, "assert inst.get_optional(100) == 100"); diff --git a/tests/test_various.rs b/tests/test_various.rs index b599da2d..ffdcf13e 100644 --- a/tests/test_various.rs +++ b/tests/test_various.rs @@ -13,7 +13,6 @@ mod common; #[pyclass] struct MutRefArg { n: i32, - token: PyToken, } #[pymethods] @@ -31,8 +30,8 @@ impl MutRefArg { fn mut_ref_arg() { let gil = Python::acquire_gil(); let py = gil.python(); - let inst1 = py.init(|t| MutRefArg { token: t, n: 0 }).unwrap(); - let inst2 = py.init(|t| MutRefArg { token: t, n: 0 }).unwrap(); + let inst1 = py.init(|| MutRefArg { n: 0 }).unwrap(); + let inst2 = py.init(|| MutRefArg { n: 0 }).unwrap(); let d = PyDict::new(py); d.set_item("inst1", &inst1).unwrap();