port `IntoPyDict` to `Bound` API

This commit is contained in:
Icxolu 2024-02-10 13:59:55 +01:00
parent 45f2b0aba5
commit e45fbe493c
34 changed files with 124 additions and 103 deletions

View File

@ -152,7 +152,7 @@ fn main() -> PyResult<()> {
let sys = py.import("sys")?; let sys = py.import("sys")?;
let version: String = sys.getattr("version")?.extract()?; let version: String = sys.getattr("version")?.extract()?;
let locals = [("os", py.import("os")?)].into_py_dict(py).as_borrowed(); let locals = [("os", py.import("os")?)].into_py_dict_bound(py);
let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"; let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?; let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?;

View File

@ -24,7 +24,7 @@ use pyo3::exceptions::PyException;
create_exception!(mymodule, CustomError, PyException); create_exception!(mymodule, CustomError, PyException);
Python::with_gil(|py| { Python::with_gil(|py| {
let ctx = [("CustomError", py.get_type::<CustomError>())].into_py_dict(py); let ctx = [("CustomError", py.get_type::<CustomError>())].into_py_dict_bound(py);
pyo3::py_run!( pyo3::py_run!(
py, py,
*ctx, *ctx,

View File

@ -283,7 +283,7 @@ Python::with_gil(|py| {
After: After:
```rust ```rust,ignore
use pyo3::prelude::*; use pyo3::prelude::*;
use pyo3::exceptions::PyTypeError; use pyo3::exceptions::PyTypeError;
use pyo3::types::{PyDict, IntoPyDict}; use pyo3::types::{PyDict, IntoPyDict};

View File

@ -93,7 +93,7 @@ fn func() -> String {
# use pyo3::wrap_pymodule; # use pyo3::wrap_pymodule;
# use pyo3::types::IntoPyDict; # use pyo3::types::IntoPyDict;
# let parent_module = wrap_pymodule!(parent_module)(py); # let parent_module = wrap_pymodule!(parent_module)(py);
# let ctx = [("parent_module", parent_module)].into_py_dict(py).as_borrowed(); # let ctx = [("parent_module", parent_module)].into_py_dict_bound(py);
# #
# py.run_bound("assert parent_module.child_module.func() == 'func'", None, Some(&ctx)).unwrap(); # py.run_bound("assert parent_module.child_module.func() == 'func'", None, Some(&ctx)).unwrap();
# }) # })

View File

@ -94,17 +94,17 @@ fn main() -> PyResult<()> {
.into(); .into();
// call object with PyDict // call object with PyDict
let kwargs = [(key1, val1)].into_py_dict(py); let kwargs = [(key1, val1)].into_py_dict_bound(py);
fun.call_bound(py, (), Some(&kwargs.as_borrowed()))?; fun.call_bound(py, (), Some(&kwargs))?;
// pass arguments as Vec // pass arguments as Vec
let kwargs = vec![(key1, val1), (key2, val2)]; let kwargs = vec![(key1, val1), (key2, val2)];
fun.call_bound(py, (), Some(&kwargs.into_py_dict(py).as_borrowed()))?; fun.call_bound(py, (), Some(&kwargs.into_py_dict_bound(py)))?;
// pass arguments as HashMap // pass arguments as HashMap
let mut kwargs = HashMap::<&str, i32>::new(); let mut kwargs = HashMap::<&str, i32>::new();
kwargs.insert(key1, 1); kwargs.insert(key1, 1);
fun.call_bound(py, (), Some(&kwargs.into_py_dict(py).as_borrowed()))?; fun.call_bound(py, (), Some(&kwargs.into_py_dict_bound(py)))?;
Ok(()) Ok(())
}) })
@ -250,10 +250,10 @@ def leaky_relu(x, slope=0.01):
let relu_result: f64 = activators.getattr("relu")?.call1((-1.0,))?.extract()?; let relu_result: f64 = activators.getattr("relu")?.call1((-1.0,))?.extract()?;
assert_eq!(relu_result, 0.0); assert_eq!(relu_result, 0.0);
let kwargs = [("slope", 0.2)].into_py_dict(py); let kwargs = [("slope", 0.2)].into_py_dict_bound(py);
let lrelu_result: f64 = activators let lrelu_result: f64 = activators
.getattr("leaky_relu")? .getattr("leaky_relu")?
.call((-1.0,), Some(kwargs))? .call((-1.0,), Some(kwargs.as_gil_ref()))?
.extract()?; .extract()?;
assert_eq!(lrelu_result, -0.2); assert_eq!(lrelu_result, -0.2);
# Ok(()) # Ok(())

View File

@ -147,7 +147,7 @@ mod test_anyhow {
let pyerr = PyErr::from(err); let pyerr = PyErr::from(err);
Python::with_gil(|py| { Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).as_borrowed(); let locals = [("err", pyerr)].into_py_dict_bound(py);
let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err(); let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents); assert_eq!(pyerr.value(py).to_string(), expected_contents);
}) })
@ -164,7 +164,7 @@ mod test_anyhow {
let pyerr = PyErr::from(err); let pyerr = PyErr::from(err);
Python::with_gil(|py| { Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).as_borrowed(); let locals = [("err", pyerr)].into_py_dict_bound(py);
let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err(); let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents); assert_eq!(pyerr.value(py).to_string(), expected_contents);
}) })

View File

@ -1109,7 +1109,7 @@ mod tests {
fn test_pyo3_offset_fixed_frompyobject_created_in_python(timestamp in 0..(i32::MAX as i64), timedelta in -86399i32..=86399i32) { fn test_pyo3_offset_fixed_frompyobject_created_in_python(timestamp in 0..(i32::MAX as i64), timedelta in -86399i32..=86399i32) {
Python::with_gil(|py| { Python::with_gil(|py| {
let globals = [("datetime", py.import("datetime").unwrap())].into_py_dict(py).as_borrowed(); let globals = [("datetime", py.import("datetime").unwrap())].into_py_dict_bound(py);
let code = format!("datetime.datetime.fromtimestamp({}).replace(tzinfo=datetime.timezone(datetime.timedelta(seconds={})))", timestamp, timedelta); let code = format!("datetime.datetime.fromtimestamp({}).replace(tzinfo=datetime.timezone(datetime.timedelta(seconds={})))", timestamp, timedelta);
let t = py.eval_bound(&code, Some(&globals), None).unwrap(); let t = py.eval_bound(&code, Some(&globals), None).unwrap();

View File

@ -152,7 +152,7 @@ mod tests {
let pyerr = PyErr::from(err); let pyerr = PyErr::from(err);
Python::with_gil(|py| { Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).as_borrowed(); let locals = [("err", pyerr)].into_py_dict_bound(py);
let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err(); let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents); assert_eq!(pyerr.value(py).to_string(), expected_contents);
}) })
@ -169,7 +169,7 @@ mod tests {
let pyerr = PyErr::from(err); let pyerr = PyErr::from(err);
Python::with_gil(|py| { Python::with_gil(|py| {
let locals = [("err", pyerr)].into_py_dict(py).as_borrowed(); let locals = [("err", pyerr)].into_py_dict_bound(py);
let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err(); let pyerr = py.run_bound("raise err", None, Some(&locals)).unwrap_err();
assert_eq!(pyerr.value(py).to_string(), expected_contents); assert_eq!(pyerr.value(py).to_string(), expected_contents);
}) })

View File

@ -33,7 +33,7 @@ where
H: hash::BuildHasher, H: hash::BuildHasher,
{ {
fn to_object(&self, py: Python<'_>) -> PyObject { fn to_object(&self, py: Python<'_>) -> PyObject {
IntoPyDict::into_py_dict(self, py).into() IntoPyDict::into_py_dict_bound(self, py).into()
} }
} }
@ -47,7 +47,7 @@ where
let iter = self let iter = self
.into_iter() .into_iter()
.map(|(k, v)| (k.into_py(py), v.into_py(py))); .map(|(k, v)| (k.into_py(py), v.into_py(py)));
IntoPyDict::into_py_dict(iter, py).into() IntoPyDict::into_py_dict_bound(iter, py).into()
} }
} }
@ -164,7 +164,7 @@ mod tests {
let mut map = hashbrown::HashMap::<i32, i32>::new(); let mut map = hashbrown::HashMap::<i32, i32>::new();
map.insert(1, 1); map.insert(1, 1);
let py_map = map.into_py_dict(py); let py_map = map.into_py_dict_bound(py);
assert_eq!(py_map.len(), 1); assert_eq!(py_map.len(), 1);
assert_eq!( assert_eq!(

View File

@ -100,7 +100,7 @@ where
H: hash::BuildHasher, H: hash::BuildHasher,
{ {
fn to_object(&self, py: Python<'_>) -> PyObject { fn to_object(&self, py: Python<'_>) -> PyObject {
IntoPyDict::into_py_dict(self, py).into() IntoPyDict::into_py_dict_bound(self, py).into()
} }
} }
@ -114,7 +114,7 @@ where
let iter = self let iter = self
.into_iter() .into_iter()
.map(|(k, v)| (k.into_py(py), v.into_py(py))); .map(|(k, v)| (k.into_py(py), v.into_py(py)));
IntoPyDict::into_py_dict(iter, py).into() IntoPyDict::into_py_dict_bound(iter, py).into()
} }
} }
@ -137,6 +137,8 @@ where
#[cfg(test)] #[cfg(test)]
mod test_indexmap { mod test_indexmap {
use crate::types::any::PyAnyMethods;
use crate::types::dict::PyDictMethods;
use crate::types::*; use crate::types::*;
use crate::{IntoPy, PyObject, Python, ToPyObject}; use crate::{IntoPy, PyObject, Python, ToPyObject};
@ -194,7 +196,7 @@ mod test_indexmap {
let mut map = indexmap::IndexMap::<i32, i32>::new(); let mut map = indexmap::IndexMap::<i32, i32>::new();
map.insert(1, 1); map.insert(1, 1);
let py_map = map.into_py_dict(py); let py_map = map.into_py_dict_bound(py);
assert_eq!(py_map.len(), 1); assert_eq!(py_map.len(), 1);
assert_eq!( assert_eq!(
@ -223,7 +225,7 @@ mod test_indexmap {
} }
} }
let py_map = map.clone().into_py_dict(py); let py_map = map.clone().into_py_dict_bound(py);
let trip_map = py_map.extract::<indexmap::IndexMap<i32, i32>>().unwrap(); let trip_map = py_map.extract::<indexmap::IndexMap<i32, i32>>().unwrap();

View File

@ -16,7 +16,7 @@ where
H: hash::BuildHasher, H: hash::BuildHasher,
{ {
fn to_object(&self, py: Python<'_>) -> PyObject { fn to_object(&self, py: Python<'_>) -> PyObject {
IntoPyDict::into_py_dict(self, py).into() IntoPyDict::into_py_dict_bound(self, py).into()
} }
} }
@ -26,7 +26,7 @@ where
V: ToPyObject, V: ToPyObject,
{ {
fn to_object(&self, py: Python<'_>) -> PyObject { fn to_object(&self, py: Python<'_>) -> PyObject {
IntoPyDict::into_py_dict(self, py).into() IntoPyDict::into_py_dict_bound(self, py).into()
} }
} }
@ -40,7 +40,7 @@ where
let iter = self let iter = self
.into_iter() .into_iter()
.map(|(k, v)| (k.into_py(py), v.into_py(py))); .map(|(k, v)| (k.into_py(py), v.into_py(py)));
IntoPyDict::into_py_dict(iter, py).into() IntoPyDict::into_py_dict_bound(iter, py).into()
} }
#[cfg(feature = "experimental-inspect")] #[cfg(feature = "experimental-inspect")]
@ -58,7 +58,7 @@ where
let iter = self let iter = self
.into_iter() .into_iter()
.map(|(k, v)| (k.into_py(py), v.into_py(py))); .map(|(k, v)| (k.into_py(py), v.into_py(py)));
IntoPyDict::into_py_dict(iter, py).into() IntoPyDict::into_py_dict_bound(iter, py).into()
} }
#[cfg(feature = "experimental-inspect")] #[cfg(feature = "experimental-inspect")]

View File

@ -71,7 +71,7 @@ macro_rules! impl_exception_boilerplate {
/// import_exception!(socket, gaierror); /// import_exception!(socket, gaierror);
/// ///
/// Python::with_gil(|py| { /// Python::with_gil(|py| {
/// let ctx = [("gaierror", py.get_type::<gaierror>())].into_py_dict(py); /// let ctx = [("gaierror", py.get_type::<gaierror>())].into_py_dict_bound(py);
/// pyo3::py_run!(py, *ctx, "import socket; assert gaierror is socket.gaierror"); /// pyo3::py_run!(py, *ctx, "import socket; assert gaierror is socket.gaierror");
/// }); /// });
/// ///
@ -864,7 +864,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let error_type = py.get_type::<CustomError>(); let error_type = py.get_type::<CustomError>();
let ctx = [("CustomError", error_type)].into_py_dict(py).as_borrowed(); let ctx = [("CustomError", error_type)].into_py_dict_bound(py);
let type_description: String = py let type_description: String = py
.eval_bound("str(CustomError)", None, Some(&ctx)) .eval_bound("str(CustomError)", None, Some(&ctx))
.unwrap() .unwrap()
@ -887,7 +887,7 @@ mod tests {
create_exception!(mymodule.exceptions, CustomError, PyException); create_exception!(mymodule.exceptions, CustomError, PyException);
Python::with_gil(|py| { Python::with_gil(|py| {
let error_type = py.get_type::<CustomError>(); let error_type = py.get_type::<CustomError>();
let ctx = [("CustomError", error_type)].into_py_dict(py).as_borrowed(); let ctx = [("CustomError", error_type)].into_py_dict_bound(py);
let type_description: String = py let type_description: String = py
.eval_bound("str(CustomError)", None, Some(&ctx)) .eval_bound("str(CustomError)", None, Some(&ctx))
.unwrap() .unwrap()
@ -906,7 +906,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let error_type = py.get_type::<CustomError>(); let error_type = py.get_type::<CustomError>();
let ctx = [("CustomError", error_type)].into_py_dict(py).as_borrowed(); let ctx = [("CustomError", error_type)].into_py_dict_bound(py);
let type_description: String = py let type_description: String = py
.eval_bound("str(CustomError)", None, Some(&ctx)) .eval_bound("str(CustomError)", None, Some(&ctx))
.unwrap() .unwrap()
@ -939,7 +939,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let error_type = py.get_type::<CustomError>(); let error_type = py.get_type::<CustomError>();
let ctx = [("CustomError", error_type)].into_py_dict(py).as_borrowed(); let ctx = [("CustomError", error_type)].into_py_dict_bound(py);
let type_description: String = py let type_description: String = py
.eval_bound("str(CustomError)", None, Some(&ctx)) .eval_bound("str(CustomError)", None, Some(&ctx))
.unwrap() .unwrap()

View File

@ -727,7 +727,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let args = PyTuple::new_bound(py, Vec::<&PyAny>::new()); let args = PyTuple::new_bound(py, Vec::<&PyAny>::new());
let kwargs = [("foo", 0u8)].into_py_dict(py); let kwargs = [("foo", 0u8)].into_py_dict_bound(py);
let err = unsafe { let err = unsafe {
function_description function_description
.extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>( .extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>(
@ -758,7 +758,7 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let args = PyTuple::new_bound(py, Vec::<&PyAny>::new()); let args = PyTuple::new_bound(py, Vec::<&PyAny>::new());
let kwargs = [(1u8, 1u8)].into_py_dict(py); let kwargs = [(1u8, 1u8)].into_py_dict_bound(py);
let err = unsafe { let err = unsafe {
function_description function_description
.extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>( .extract_arguments_tuple_dict::<NoVarargs, NoVarkeywords>(

View File

@ -1765,7 +1765,7 @@ mod tests {
"{'x': 1}", "{'x': 1}",
); );
assert_repr( assert_repr(
obj.call(py, (), Some([('x', 1)].into_py_dict(py))) obj.call_bound(py, (), Some(&[('x', 1)].into_py_dict_bound(py)))
.unwrap() .unwrap()
.as_ref(py), .as_ref(py),
"{'x': 1}", "{'x': 1}",

View File

@ -221,7 +221,7 @@
//! let sys = py.import("sys")?; //! let sys = py.import("sys")?;
//! let version: String = sys.getattr("version")?.extract()?; //! let version: String = sys.getattr("version")?.extract()?;
//! //!
//! let locals = [("os", py.import("os")?)].into_py_dict(py).as_borrowed(); //! let locals = [("os", py.import("os")?)].into_py_dict_bound(py);
//! let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"; //! let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
//! let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?; //! let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?;
//! //!

View File

@ -73,7 +73,7 @@
/// } /// }
/// ///
/// Python::with_gil(|py| { /// Python::with_gil(|py| {
/// let locals = [("C", py.get_type::<MyClass>())].into_py_dict(py); /// let locals = [("C", py.get_type::<MyClass>())].into_py_dict_bound(py);
/// pyo3::py_run!(py, *locals, "c = C()"); /// pyo3::py_run!(py, *locals, "c = C()");
/// }); /// });
/// ``` /// ```
@ -99,11 +99,12 @@ macro_rules! py_run_impl {
($py:expr, $($val:ident)+, $code:expr) => {{ ($py:expr, $($val:ident)+, $code:expr) => {{
use $crate::types::IntoPyDict; use $crate::types::IntoPyDict;
use $crate::ToPyObject; use $crate::ToPyObject;
let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict($py); let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict_bound($py);
$crate::py_run_impl!($py, *d, $code) $crate::py_run_impl!($py, *d, $code)
}}; }};
($py:expr, *$dict:expr, $code:expr) => {{ ($py:expr, *$dict:expr, $code:expr) => {{
use ::std::option::Option::*; use ::std::option::Option::*;
#[allow(unused_imports)]
use $crate::PyNativeType; use $crate::PyNativeType;
if let ::std::result::Result::Err(e) = $py.run_bound($code, None, Some(&$dict.as_borrowed())) { if let ::std::result::Result::Err(e) = $py.run_bound($code, None, Some(&$dict.as_borrowed())) {
e.print($py); e.print($py);

View File

@ -1132,7 +1132,7 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!(v, 1); assert_eq!(v, 1);
let d = [("foo", 13)].into_py_dict(py).as_borrowed(); let d = [("foo", 13)].into_py_dict_bound(py);
// Inject our own global namespace // Inject our own global namespace
let v: i32 = py let v: i32 = py

View File

@ -35,12 +35,11 @@ mod inner {
// Case1: idents & no err_msg // Case1: idents & no err_msg
($py:expr, $($val:ident)+, $code:expr, $err:ident) => {{ ($py:expr, $($val:ident)+, $code:expr, $err:ident) => {{
use pyo3::types::IntoPyDict; use pyo3::types::IntoPyDict;
let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict($py); let d = [$((stringify!($val), $val.to_object($py)),)+].into_py_dict_bound($py);
py_expect_exception!($py, *d, $code, $err) py_expect_exception!($py, *d, $code, $err)
}}; }};
// Case2: dict & no err_msg // Case2: dict & no err_msg
($py:expr, *$dict:expr, $code:expr, $err:ident) => {{ ($py:expr, *$dict:expr, $code:expr, $err:ident) => {{
use pyo3::PyNativeType;
let res = $py.run_bound($code, None, Some(&$dict.as_borrowed())); let res = $py.run_bound($code, None, Some(&$dict.as_borrowed()));
let err = res.expect_err(&format!("Did not raise {}", stringify!($err))); let err = res.expect_err(&format!("Did not raise {}", stringify!($err)));
if !err.matches($py, $py.get_type::<pyo3::exceptions::$err>()) { if !err.matches($py, $py.get_type::<pyo3::exceptions::$err>()) {
@ -117,8 +116,10 @@ mod inner {
impl<'py> CatchWarnings<'py> { impl<'py> CatchWarnings<'py> {
pub fn enter<R>(py: Python<'py>, f: impl FnOnce(&PyList) -> PyResult<R>) -> PyResult<R> { pub fn enter<R>(py: Python<'py>, f: impl FnOnce(&PyList) -> PyResult<R>) -> PyResult<R> {
let warnings = py.import("warnings")?; let warnings = py.import("warnings")?;
let kwargs = [("record", true)].into_py_dict(py); let kwargs = [("record", true)].into_py_dict_bound(py);
let catch_warnings = warnings.getattr("catch_warnings")?.call((), Some(kwargs))?; let catch_warnings = warnings
.getattr("catch_warnings")?
.call((), Some(kwargs.as_gil_ref()))?;
let list = catch_warnings.call_method0("__enter__")?.extract()?; let list = catch_warnings.call_method0("__enter__")?.extract()?;
let _guard = Self { catch_warnings }; let _guard = Self { catch_warnings };
f(list) f(list)

View File

@ -2400,8 +2400,8 @@ class NonHeapNonDescriptorInt:
fn test_call_with_kwargs() { fn test_call_with_kwargs() {
Python::with_gil(|py| { Python::with_gil(|py| {
let list = vec![3, 6, 5, 4, 7].to_object(py); let list = vec![3, 6, 5, 4, 7].to_object(py);
let dict = vec![("reverse", true)].into_py_dict(py); let dict = vec![("reverse", true)].into_py_dict_bound(py);
list.call_method(py, "sort", (), Some(dict)).unwrap(); list.call_method_bound(py, "sort", (), Some(&dict)).unwrap();
assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]); assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]);
}); });
} }

View File

@ -146,13 +146,13 @@ impl PyDict {
/// ///
/// ```rust /// ```rust
/// use pyo3::prelude::*; /// use pyo3::prelude::*;
/// use pyo3::types::{PyDict, IntoPyDict}; /// use pyo3::types::{IntoPyDict};
/// use pyo3::exceptions::{PyTypeError, PyKeyError}; /// use pyo3::exceptions::{PyTypeError, PyKeyError};
/// ///
/// # fn main() { /// # fn main() {
/// # let _ = /// # let _ =
/// Python::with_gil(|py| -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> {
/// let dict: &PyDict = [("a", 1)].into_py_dict(py); /// let dict = &[("a", 1)].into_py_dict_bound(py);
/// // `a` is in the dictionary, with value 1 /// // `a` is in the dictionary, with value 1
/// assert!(dict.get_item("a")?.map_or(Ok(false), |x| x.eq(1))?); /// assert!(dict.get_item("a")?.map_or(Ok(false), |x| x.eq(1))?);
/// // `b` is not in the dictionary /// // `b` is not in the dictionary
@ -161,7 +161,7 @@ impl PyDict {
/// assert!(dict.get_item(dict).unwrap_err().is_instance_of::<PyTypeError>(py)); /// assert!(dict.get_item(dict).unwrap_err().is_instance_of::<PyTypeError>(py));
/// ///
/// // `PyAny::get_item("b")` will raise a `KeyError` instead of returning `None` /// // `PyAny::get_item("b")` will raise a `KeyError` instead of returning `None`
/// let any: &PyAny = dict.as_ref(); /// let any = dict.as_any();
/// assert!(any.get_item("b").unwrap_err().is_instance_of::<PyKeyError>(py)); /// assert!(any.get_item("b").unwrap_err().is_instance_of::<PyKeyError>(py));
/// Ok(()) /// Ok(())
/// }); /// });
@ -650,10 +650,23 @@ impl<'py> IntoIterator for Bound<'py, PyDict> {
/// Conversion trait that allows a sequence of tuples to be converted into `PyDict` /// Conversion trait that allows a sequence of tuples to be converted into `PyDict`
/// Primary use case for this trait is `call` and `call_method` methods as keywords argument. /// Primary use case for this trait is `call` and `call_method` methods as keywords argument.
pub trait IntoPyDict { pub trait IntoPyDict: Sized {
/// Converts self into a `PyDict` object pointer. Whether pointer owned or borrowed /// Converts self into a `PyDict` object pointer. Whether pointer owned or borrowed
/// depends on implementation. /// depends on implementation.
fn into_py_dict(self, py: Python<'_>) -> &PyDict; #[cfg_attr(
not(feature = "gil-refs"),
deprecated(
since = "0.21.0",
note = "`IntoPyDict::into_py_dict` will be replaced by `IntoPyDict::into_py_dict_bound` in a future PyO3 version"
)
)]
fn into_py_dict(self, py: Python<'_>) -> &PyDict {
Self::into_py_dict_bound(self, py).into_gil_ref()
}
/// Converts self into a `PyDict` object pointer. Whether pointer owned or borrowed
/// depends on implementation.
fn into_py_dict_bound(self, py: Python<'_>) -> Bound<'_, PyDict>;
} }
impl<T, I> IntoPyDict for I impl<T, I> IntoPyDict for I
@ -661,8 +674,8 @@ where
T: PyDictItem, T: PyDictItem,
I: IntoIterator<Item = T>, I: IntoIterator<Item = T>,
{ {
fn into_py_dict(self, py: Python<'_>) -> &PyDict { fn into_py_dict_bound(self, py: Python<'_>) -> Bound<'_, PyDict> {
let dict = PyDict::new(py); let dict = PyDict::new_bound(py);
for item in self { for item in self {
dict.set_item(item.key(), item.value()) dict.set_item(item.key(), item.value())
.expect("Failed to set_item on dict"); .expect("Failed to set_item on dict");
@ -723,7 +736,7 @@ mod tests {
#[test] #[test]
fn test_new() { fn test_new() {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = [(7, 32)].into_py_dict(py); let dict = [(7, 32)].into_py_dict_bound(py);
assert_eq!( assert_eq!(
32, 32,
dict.get_item(7i32) dict.get_item(7i32)
@ -783,7 +796,7 @@ mod tests {
#[test] #[test]
fn test_copy() { fn test_copy() {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = [(7, 32)].into_py_dict(py); let dict = [(7, 32)].into_py_dict_bound(py);
let ndict = dict.copy().unwrap(); let ndict = dict.copy().unwrap();
assert_eq!( assert_eq!(
@ -905,7 +918,7 @@ mod tests {
{ {
let _pool = unsafe { crate::GILPool::new() }; let _pool = unsafe { crate::GILPool::new() };
cnt = obj.get_refcnt(); cnt = obj.get_refcnt();
let _dict = [(10, obj)].into_py_dict(py); let _dict = [(10, obj)].into_py_dict_bound(py);
} }
{ {
assert_eq!(cnt, obj.get_refcnt()); assert_eq!(cnt, obj.get_refcnt());
@ -1150,7 +1163,7 @@ mod tests {
let mut map = HashMap::<i32, i32>::new(); let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1); map.insert(1, 1);
let py_map = map.into_py_dict(py); let py_map = map.into_py_dict_bound(py);
assert_eq!(py_map.len(), 1); assert_eq!(py_map.len(), 1);
assert_eq!( assert_eq!(
@ -1171,7 +1184,7 @@ mod tests {
let mut map = BTreeMap::<i32, i32>::new(); let mut map = BTreeMap::<i32, i32>::new();
map.insert(1, 1); map.insert(1, 1);
let py_map = map.into_py_dict(py); let py_map = map.into_py_dict_bound(py);
assert_eq!(py_map.len(), 1); assert_eq!(py_map.len(), 1);
assert_eq!( assert_eq!(
@ -1190,7 +1203,7 @@ mod tests {
fn test_vec_into_dict() { fn test_vec_into_dict() {
Python::with_gil(|py| { Python::with_gil(|py| {
let vec = vec![("a", 1), ("b", 2), ("c", 3)]; let vec = vec![("a", 1), ("b", 2), ("c", 3)];
let py_map = vec.into_py_dict(py); let py_map = vec.into_py_dict_bound(py);
assert_eq!(py_map.len(), 3); assert_eq!(py_map.len(), 3);
assert_eq!( assert_eq!(
@ -1209,7 +1222,7 @@ mod tests {
fn test_slice_into_dict() { fn test_slice_into_dict() {
Python::with_gil(|py| { Python::with_gil(|py| {
let arr = [("a", 1), ("b", 2), ("c", 3)]; let arr = [("a", 1), ("b", 2), ("c", 3)];
let py_map = arr.into_py_dict(py); let py_map = arr.into_py_dict_bound(py);
assert_eq!(py_map.len(), 3); assert_eq!(py_map.len(), 3);
assert_eq!( assert_eq!(
@ -1230,7 +1243,7 @@ mod tests {
let mut map = HashMap::<i32, i32>::new(); let mut map = HashMap::<i32, i32>::new();
map.insert(1, 1); map.insert(1, 1);
let py_map = map.into_py_dict(py); let py_map = map.into_py_dict_bound(py);
assert_eq!(py_map.as_mapping().len().unwrap(), 1); assert_eq!(py_map.as_mapping().len().unwrap(), 1);
assert_eq!( assert_eq!(
@ -1246,12 +1259,12 @@ mod tests {
} }
#[cfg(not(PyPy))] #[cfg(not(PyPy))]
fn abc_dict(py: Python<'_>) -> &PyDict { fn abc_dict(py: Python<'_>) -> Bound<'_, PyDict> {
let mut map = HashMap::<&'static str, i32>::new(); let mut map = HashMap::<&'static str, i32>::new();
map.insert("a", 1); map.insert("a", 1);
map.insert("b", 2); map.insert("b", 2);
map.insert("c", 3); map.insert("c", 3);
map.into_py_dict(py) map.into_py_dict_bound(py)
} }
#[test] #[test]
@ -1260,7 +1273,9 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = abc_dict(py); let dict = abc_dict(py);
let keys = dict.call_method0("keys").unwrap(); let keys = dict.call_method0("keys").unwrap();
assert!(keys.is_instance(py.get_type::<PyDictKeys>()).unwrap()); assert!(keys
.is_instance(&py.get_type::<PyDictKeys>().as_borrowed())
.unwrap());
}) })
} }
@ -1270,7 +1285,9 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = abc_dict(py); let dict = abc_dict(py);
let values = dict.call_method0("values").unwrap(); let values = dict.call_method0("values").unwrap();
assert!(values.is_instance(py.get_type::<PyDictValues>()).unwrap()); assert!(values
.is_instance(&py.get_type::<PyDictValues>().as_borrowed())
.unwrap());
}) })
} }
@ -1280,15 +1297,17 @@ mod tests {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = abc_dict(py); let dict = abc_dict(py);
let items = dict.call_method0("items").unwrap(); let items = dict.call_method0("items").unwrap();
assert!(items.is_instance(py.get_type::<PyDictItems>()).unwrap()); assert!(items
.is_instance(&py.get_type::<PyDictItems>().as_borrowed())
.unwrap());
}) })
} }
#[test] #[test]
fn dict_update() { fn dict_update() {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = [("a", 1), ("b", 2), ("c", 3)].into_py_dict(py); let dict = [("a", 1), ("b", 2), ("c", 3)].into_py_dict_bound(py);
let other = [("b", 4), ("c", 5), ("d", 6)].into_py_dict(py); let other = [("b", 4), ("c", 5), ("d", 6)].into_py_dict_bound(py);
dict.update(other.as_mapping()).unwrap(); dict.update(other.as_mapping()).unwrap();
assert_eq!(dict.len(), 4); assert_eq!(dict.len(), 4);
assert_eq!( assert_eq!(
@ -1358,8 +1377,8 @@ mod tests {
#[test] #[test]
fn dict_update_if_missing() { fn dict_update_if_missing() {
Python::with_gil(|py| { Python::with_gil(|py| {
let dict = [("a", 1), ("b", 2), ("c", 3)].into_py_dict(py); let dict = [("a", 1), ("b", 2), ("c", 3)].into_py_dict_bound(py);
let other = [("b", 4), ("c", 5), ("d", 6)].into_py_dict(py); let other = [("b", 4), ("c", 5), ("d", 6)].into_py_dict_bound(py);
dict.update_if_missing(other.as_mapping()).unwrap(); dict.update_if_missing(other.as_mapping()).unwrap();
assert_eq!(dict.len(), 4); assert_eq!(dict.len(), 4);
assert_eq!( assert_eq!(

View File

@ -57,7 +57,7 @@ fn test_buffer() {
}, },
) )
.unwrap(); .unwrap();
let env = [("ob", instance)].into_py_dict(py); let env = [("ob", instance)].into_py_dict_bound(py);
py_assert!(py, *env, "bytes(ob) == b' 23'"); py_assert!(py, *env, "bytes(ob) == b' 23'");
}); });
@ -122,7 +122,7 @@ fn test_releasebuffer_unraisable_error() {
let capture = UnraisableCapture::install(py); let capture = UnraisableCapture::install(py);
let instance = Py::new(py, ReleaseBufferError {}).unwrap(); let instance = Py::new(py, ReleaseBufferError {}).unwrap();
let env = [("ob", instance.clone())].into_py_dict(py); let env = [("ob", instance.clone())].into_py_dict_bound(py);
assert!(capture.borrow(py).capture.is_none()); assert!(capture.borrow(py).capture.is_none());

View File

@ -29,7 +29,10 @@ fn empty_class_with_new() {
// Calling with arbitrary args or kwargs is not ok // Calling with arbitrary args or kwargs is not ok
assert!(typeobj.call(("some", "args"), None).is_err()); assert!(typeobj.call(("some", "args"), None).is_err());
assert!(typeobj assert!(typeobj
.call((), Some([("some", "kwarg")].into_py_dict(py))) .call(
(),
Some([("some", "kwarg")].into_py_dict_bound(py).as_gil_ref())
)
.is_err()); .is_err());
}); });
} }

View File

@ -68,7 +68,7 @@ fn test_coroutine_qualname() {
("my_fn", wrap_pyfunction!(my_fn, gil).unwrap().deref()), ("my_fn", wrap_pyfunction!(my_fn, gil).unwrap().deref()),
("MyClass", gil.get_type::<MyClass>()), ("MyClass", gil.get_type::<MyClass>()),
] ]
.into_py_dict(gil); .into_py_dict_bound(gil);
py_run!(gil, *locals, &handle_windows(test)); py_run!(gil, *locals, &handle_windows(test));
}) })
} }
@ -286,7 +286,7 @@ fn test_async_method_receiver() {
assert False assert False
assert asyncio.run(coro3) == 1 assert asyncio.run(coro3) == 1
"#; "#;
let locals = [("Counter", gil.get_type::<Counter>())].into_py_dict(gil); let locals = [("Counter", gil.get_type::<Counter>())].into_py_dict_bound(gil);
py_run!(gil, *locals, test); py_run!(gil, *locals, test);
}) })
} }

View File

@ -12,9 +12,7 @@ fn _get_subclasses<'py>(
// Import the class from Python and create some subclasses // Import the class from Python and create some subclasses
let datetime = py.import("datetime")?; let datetime = py.import("datetime")?;
let locals = [(py_type, datetime.getattr(py_type)?)] let locals = [(py_type, datetime.getattr(py_type)?)].into_py_dict_bound(py);
.into_py_dict(py)
.as_borrowed();
let make_subclass_py = format!("class Subklass({}):\n pass", py_type); let make_subclass_py = format!("class Subklass({}):\n pass", py_type);
@ -23,7 +21,6 @@ fn _get_subclasses<'py>(
py.run_bound(&make_subclass_py, None, Some(&locals))?; py.run_bound(&make_subclass_py, None, Some(&locals))?;
py.run_bound(make_sub_subclass_py, None, Some(&locals))?; py.run_bound(make_sub_subclass_py, None, Some(&locals))?;
let locals = locals.as_borrowed();
// Construct an instance of the base class // Construct an instance of the base class
let obj = py.eval_bound(&format!("{}({})", py_type, args), None, Some(&locals))?; let obj = py.eval_bound(&format!("{}({})", py_type, args), None, Some(&locals))?;
@ -125,7 +122,7 @@ fn test_datetime_utc() {
let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, Some(utc)).unwrap(); let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, Some(utc)).unwrap();
let locals = [("dt", dt)].into_py_dict(py).as_borrowed(); let locals = [("dt", dt)].into_py_dict_bound(py);
let offset: f32 = py let offset: f32 = py
.eval_bound("dt.utcoffset().total_seconds()", None, Some(&locals)) .eval_bound("dt.utcoffset().total_seconds()", None, Some(&locals))

View File

@ -6,7 +6,7 @@ use pyo3::types::IntoPyDict;
fn iter_dict_nosegv() { fn iter_dict_nosegv() {
Python::with_gil(|py| { Python::with_gil(|py| {
const LEN: usize = 10_000_000; const LEN: usize = 10_000_000;
let dict = (0..LEN as u64).map(|i| (i, i * 2)).into_py_dict(py); let dict = (0..LEN as u64).map(|i| (i, i * 2)).into_py_dict_bound(py);
let mut sum = 0; let mut sum = 0;
for (k, _v) in dict { for (k, _v) in dict {
let i: u64 = k.extract().unwrap(); let i: u64 = k.extract().unwrap();

View File

@ -64,7 +64,7 @@ fn class_with_properties() {
py_run!(py, inst, "assert inst.get_num() == inst.unwrapped == 42"); py_run!(py, inst, "assert inst.get_num() == inst.unwrapped == 42");
py_run!(py, inst, "assert inst.data_list == [42]"); py_run!(py, inst, "assert inst.data_list == [42]");
let d = [("C", py.get_type::<ClassWithProperties>())].into_py_dict(py); let d = [("C", py.get_type::<ClassWithProperties>())].into_py_dict_bound(py);
py_assert!(py, *d, "C.DATA.__doc__ == 'a getter for data'"); py_assert!(py, *d, "C.DATA.__doc__ == 'a getter for data'");
}); });
} }

View File

@ -20,9 +20,7 @@ struct SubclassAble {}
#[test] #[test]
fn subclass() { fn subclass() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("SubclassAble", py.get_type::<SubclassAble>())] let d = [("SubclassAble", py.get_type::<SubclassAble>())].into_py_dict_bound(py);
.into_py_dict(py)
.as_borrowed();
py.run_bound( py.run_bound(
"class A(SubclassAble): pass\nassert issubclass(A, SubclassAble)", "class A(SubclassAble): pass\nassert issubclass(A, SubclassAble)",
@ -99,7 +97,7 @@ fn call_base_and_sub_methods() {
fn mutation_fails() { fn mutation_fails() {
Python::with_gil(|py| { Python::with_gil(|py| {
let obj = PyCell::new(py, SubClass::new()).unwrap(); let obj = PyCell::new(py, SubClass::new()).unwrap();
let global = [("obj", obj)].into_py_dict(py).as_borrowed(); let global = [("obj", obj)].into_py_dict_bound(py);
let e = py let e = py
.run_bound( .run_bound(
"obj.base_set(lambda: obj.sub_set_and_ret(1))", "obj.base_set(lambda: obj.sub_set_and_ret(1))",
@ -277,7 +275,7 @@ mod inheriting_native_type {
fn custom_exception() { fn custom_exception() {
Python::with_gil(|py| { Python::with_gil(|py| {
let cls = py.get_type::<CustomException>(); let cls = py.get_type::<CustomException>();
let dict = [("cls", cls)].into_py_dict(py).as_borrowed(); let dict = [("cls", cls)].into_py_dict_bound(py);
let res = py.run_bound( let res = py.run_bound(
"e = cls('hello'); assert str(e) == 'hello'; assert e.context == 'Hello :)'; raise e", "e = cls('hello'); assert str(e) == 'hello'; assert e.context == 'Hello :)'; raise e",
None, None,

View File

@ -23,7 +23,7 @@ impl MacroDocs {
#[test] #[test]
fn meth_doc() { fn meth_doc() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("C", py.get_type::<MacroDocs>())].into_py_dict(py); let d = [("C", py.get_type::<MacroDocs>())].into_py_dict_bound(py);
py_assert!( py_assert!(
py, py,
*d, *d,

View File

@ -68,8 +68,8 @@ impl Mapping {
} }
/// Return a dict with `m = Mapping(['1', '2', '3'])`. /// Return a dict with `m = Mapping(['1', '2', '3'])`.
fn map_dict(py: Python<'_>) -> &pyo3::types::PyDict { fn map_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
let d = [("Mapping", py.get_type::<Mapping>())].into_py_dict(py); let d = [("Mapping", py.get_type::<Mapping>())].into_py_dict_bound(py);
py_run!(py, *d, "m = Mapping(['1', '2', '3'])"); py_run!(py, *d, "m = Mapping(['1', '2', '3'])");
d d
} }

View File

@ -89,7 +89,7 @@ impl ClassMethod {
#[test] #[test]
fn class_method() { fn class_method() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("C", py.get_type::<ClassMethod>())].into_py_dict(py); let d = [("C", py.get_type::<ClassMethod>())].into_py_dict_bound(py);
py_assert!(py, *d, "C.method() == 'ClassMethod.method()!'"); py_assert!(py, *d, "C.method() == 'ClassMethod.method()!'");
py_assert!(py, *d, "C().method() == 'ClassMethod.method()!'"); py_assert!(py, *d, "C().method() == 'ClassMethod.method()!'");
py_assert!( py_assert!(
@ -116,7 +116,7 @@ impl ClassMethodWithArgs {
#[test] #[test]
fn class_method_with_args() { fn class_method_with_args() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("C", py.get_type::<ClassMethodWithArgs>())].into_py_dict(py); let d = [("C", py.get_type::<ClassMethodWithArgs>())].into_py_dict_bound(py);
py_assert!( py_assert!(
py, py,
*d, *d,
@ -147,7 +147,7 @@ fn static_method() {
Python::with_gil(|py| { Python::with_gil(|py| {
assert_eq!(StaticMethod::method(py), "StaticMethod.method()!"); assert_eq!(StaticMethod::method(py), "StaticMethod.method()!");
let d = [("C", py.get_type::<StaticMethod>())].into_py_dict(py); let d = [("C", py.get_type::<StaticMethod>())].into_py_dict_bound(py);
py_assert!(py, *d, "C.method() == 'StaticMethod.method()!'"); py_assert!(py, *d, "C.method() == 'StaticMethod.method()!'");
py_assert!(py, *d, "C().method() == 'StaticMethod.method()!'"); py_assert!(py, *d, "C().method() == 'StaticMethod.method()!'");
py_assert!(py, *d, "C.method.__doc__ == 'Test static method.'"); py_assert!(py, *d, "C.method.__doc__ == 'Test static method.'");
@ -171,7 +171,7 @@ fn static_method_with_args() {
Python::with_gil(|py| { Python::with_gil(|py| {
assert_eq!(StaticMethodWithArgs::method(py, 1234), "0x4d2"); assert_eq!(StaticMethodWithArgs::method(py, 1234), "0x4d2");
let d = [("C", py.get_type::<StaticMethodWithArgs>())].into_py_dict(py); let d = [("C", py.get_type::<StaticMethodWithArgs>())].into_py_dict_bound(py);
py_assert!(py, *d, "C.method(1337) == '0x539'"); py_assert!(py, *d, "C.method(1337) == '0x539'");
}); });
} }
@ -669,7 +669,7 @@ impl MethDocs {
#[test] #[test]
fn meth_doc() { fn meth_doc() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("C", py.get_type::<MethDocs>())].into_py_dict(py); let d = [("C", py.get_type::<MethDocs>())].into_py_dict_bound(py);
py_assert!(py, *d, "C.__doc__ == 'A class with \"documentation\".'"); py_assert!(py, *d, "C.__doc__ == 'A class with \"documentation\".'");
py_assert!( py_assert!(
py, py,
@ -753,7 +753,7 @@ fn method_with_pyclassarg() {
Python::with_gil(|py| { Python::with_gil(|py| {
let obj1 = PyCell::new(py, MethodWithPyClassArg { value: 10 }).unwrap(); let obj1 = PyCell::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let obj2 = PyCell::new(py, MethodWithPyClassArg { value: 10 }).unwrap(); let obj2 = PyCell::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let d = [("obj1", obj1), ("obj2", obj2)].into_py_dict(py); 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(obj2); assert obj.value == 20");
py_run!(py, *d, "obj = obj1.add_pyref(obj2); assert obj.value == 20"); py_run!(py, *d, "obj = obj1.add_pyref(obj2); assert obj.value == 20");
py_run!(py, *d, "obj = obj1.optional_add(); assert obj.value == 20"); py_run!(py, *d, "obj = obj1.optional_add(); assert obj.value == 20");

View File

@ -74,7 +74,7 @@ fn test_module_with_functions() {
"module_with_functions", "module_with_functions",
wrap_pymodule!(module_with_functions)(py), wrap_pymodule!(module_with_functions)(py),
)] )]
.into_py_dict(py); .into_py_dict_bound(py);
py_assert!( py_assert!(
py, py,
@ -127,7 +127,7 @@ fn test_module_renaming() {
use pyo3::wrap_pymodule; use pyo3::wrap_pymodule;
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("different_name", wrap_pymodule!(some_name)(py))].into_py_dict(py); let d = [("different_name", wrap_pymodule!(some_name)(py))].into_py_dict_bound(py);
py_run!(py, *d, "assert different_name.__name__ == 'other_name'"); py_run!(py, *d, "assert different_name.__name__ == 'other_name'");
}); });

View File

@ -90,7 +90,7 @@ fn test_basic() {
pyo3::Python::with_gil(|py| { pyo3::Python::with_gil(|py| {
let module = pyo3::wrap_pymodule!(basic_module)(py); let module = pyo3::wrap_pymodule!(basic_module)(py);
let cls = py.get_type::<BasicClass>(); let cls = py.get_type::<BasicClass>();
let d = pyo3::types::IntoPyDict::into_py_dict( let d = pyo3::types::IntoPyDict::into_py_dict_bound(
[ [
("mod", module.as_ref(py).as_ref()), ("mod", module.as_ref(py).as_ref()),
("cls", cls.as_ref()), ("cls", cls.as_ref()),

View File

@ -105,8 +105,8 @@ impl ByteSequence {
} }
/// Return a dict with `s = ByteSequence([1, 2, 3])`. /// Return a dict with `s = ByteSequence([1, 2, 3])`.
fn seq_dict(py: Python<'_>) -> &pyo3::types::PyDict { fn seq_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
let d = [("ByteSequence", py.get_type::<ByteSequence>())].into_py_dict(py); let d = [("ByteSequence", py.get_type::<ByteSequence>())].into_py_dict_bound(py);
// Though we can construct `s` in Rust, let's test `__new__` works. // Though we can construct `s` in Rust, let's test `__new__` works.
py_run!(py, *d, "s = ByteSequence([1, 2, 3])"); py_run!(py, *d, "s = ByteSequence([1, 2, 3])");
d d
@ -138,7 +138,7 @@ fn test_setitem() {
#[test] #[test]
fn test_delitem() { fn test_delitem() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("ByteSequence", py.get_type::<ByteSequence>())].into_py_dict(py); let d = [("ByteSequence", py.get_type::<ByteSequence>())].into_py_dict_bound(py);
py_run!( py_run!(
py, py,
@ -234,7 +234,7 @@ fn test_repeat() {
#[test] #[test]
fn test_inplace_repeat() { fn test_inplace_repeat() {
Python::with_gil(|py| { Python::with_gil(|py| {
let d = [("ByteSequence", py.get_type::<ByteSequence>())].into_py_dict(py); let d = [("ByteSequence", py.get_type::<ByteSequence>())].into_py_dict_bound(py);
py_run!( py_run!(
py, py,

View File

@ -37,8 +37,8 @@ impl Count5 {
} }
/// Return a dict with `s = Count5()`. /// Return a dict with `s = Count5()`.
fn test_dict(py: Python<'_>) -> &pyo3::types::PyDict { fn test_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
let d = [("Count5", py.get_type::<Count5>())].into_py_dict(py); let d = [("Count5", py.get_type::<Count5>())].into_py_dict_bound(py);
// Though we can construct `s` in Rust, let's test `__new__` works. // Though we can construct `s` in Rust, let's test `__new__` works.
py_run!(py, *d, "s = Count5()"); py_run!(py, *d, "s = Count5()");
d d