From 711155d7ad59fe22024279882cfade9affb3b4e7 Mon Sep 17 00:00:00 2001 From: Miles Granger Date: Wed, 20 Mar 2019 19:37:27 +0100 Subject: [PATCH] Update tests & docs with IntoPyDict::into_py_dict(py) --- README.md | 5 ++--- guide/src/conversions.md | 3 +-- guide/src/exception.md | 6 ++---- guide/src/get_started.md | 5 ++--- guide/src/module.md | 3 +-- src/exceptions.rs | 17 +++++++---------- src/lib.rs | 5 ++--- src/python.rs | 5 ++--- src/types/dict.rs | 9 +++------ tests/common.rs | 12 ++++++++---- tests/test_buffer_protocol.rs | 8 +++----- tests/test_datetime.rs | 8 +++----- tests/test_dunder.rs | 5 ++--- tests/test_inheritance.rs | 6 ++---- tests/test_methods.rs | 23 ++++++++--------------- tests/test_module.rs | 12 ++++-------- tests/test_various.rs | 6 ++---- 17 files changed, 54 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index bb7645d6..7fe39af6 100644 --- a/README.md +++ b/README.md @@ -103,15 +103,14 @@ Example program displaying the value of `sys.version`: extern crate pyo3; use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; fn main() -> PyResult<()> { let gil = Python::acquire_gil(); let py = gil.python(); let sys = py.import("sys")?; let version: String = sys.get("version")?.extract()?; - let locals = PyDict::new(py); - locals.set_item("os", py.import("os")?)?; + let locals = [("os", py.import("os")?)].into_py_dict(py); let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"; let user: String = py.eval(code, None, Some(&locals))?.extract()?; println!("Hello {}, I'm Python {}", user, version); diff --git a/guide/src/conversions.md b/guide/src/conversions.md index 1673b3b0..bd0d7ea2 100644 --- a/guide/src/conversions.md +++ b/guide/src/conversions.md @@ -87,8 +87,7 @@ fn main() { let obj = SomeObject::new(py); // call object with PyDict - let kwargs = PyDict::new(py); - kwargs.set_item(key1, val1); + let kwargs = [(key1, val1)].into_py_dict(py); obj.call(py, (), Some(kwargs)); // pass arguments as Vec diff --git a/guide/src/exception.md b/guide/src/exception.md index b1ab5dca..f8af952c 100644 --- a/guide/src/exception.md +++ b/guide/src/exception.md @@ -20,7 +20,7 @@ For example: # extern crate pyo3; use pyo3::prelude::*; use pyo3::create_exception; -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; use pyo3::exceptions::Exception; create_exception!(mymodule, CustomError, Exception); @@ -28,9 +28,7 @@ create_exception!(mymodule, CustomError, Exception); fn main() { let gil = Python::acquire_gil(); let py = gil.python(); - let ctx = PyDict::new(py); - - ctx.set_item("CustomError", py.get_type::()).unwrap(); + let ctx = [("CustomError", py.get_type::())].into_py_dict(py); py.run("assert str(CustomError) == \"\"", None, Some(&ctx)).unwrap(); py.run("assert CustomError('oops').args == ('oops',)", None, Some(&ctx)).unwrap(); diff --git a/guide/src/get_started.md b/guide/src/get_started.md index 53ef35f3..c20e286c 100644 --- a/guide/src/get_started.md +++ b/guide/src/get_started.md @@ -92,7 +92,7 @@ Example program displaying the value of `sys.version`: ```rust # extern crate pyo3; use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; fn main() -> PyResult<()> { let gil = Python::acquire_gil(); @@ -100,8 +100,7 @@ fn main() -> PyResult<()> { let sys = py.import("sys")?; let version: String = sys.get("version")?.extract()?; - let locals = PyDict::new(py); - locals.set_item("os", py.import("os")?)?; + let locals = [("os", py.import("os")?)].into_py_dict(py); let user: String = py.eval("os.getenv('USER') or os.getenv('USERNAME')", None, Some(&locals))?.extract()?; println!("Hello {}, I'm Python {}", user, version); diff --git a/guide/src/module.md b/guide/src/module.md index 00c7e6de..4ceeb789 100644 --- a/guide/src/module.md +++ b/guide/src/module.md @@ -83,8 +83,7 @@ fn nested_call() { let gil = GILGuard::acquire(); let py = gil.python(); let supermodule = wrap_pymodule!(supermodule)(py); - let ctx = PyDict::new(py); - ctx.set_item("supermodule", supermodule); + let ctx = [("supermodule", supermodule)].into_py_dict(py); py.run("assert supermodule.submodule.subfuntion() == 'Subfunction'", None, Some(&ctx)).unwrap(); } diff --git a/src/exceptions.rs b/src/exceptions.rs index 8faaac8b..1cee6c37 100644 --- a/src/exceptions.rs +++ b/src/exceptions.rs @@ -52,7 +52,7 @@ macro_rules! impl_exception_boilerplate { /// # Example /// ``` /// use pyo3::import_exception; -/// use pyo3::types::PyDict; +/// use pyo3::types::IntoPyDict; /// use pyo3::Python; /// /// import_exception!(socket, gaierror); @@ -60,9 +60,8 @@ macro_rules! impl_exception_boilerplate { /// fn main() { /// let gil = Python::acquire_gil(); /// let py = gil.python(); -/// let ctx = PyDict::new(py); /// -/// ctx.set_item("gaierror", py.get_type::()).unwrap(); +/// let ctx = [("gaierror", py.get_type::())].into_py_dict(py); /// py.run( /// "import socket; assert gaierror is socket.gaierror", /// None, @@ -133,7 +132,7 @@ macro_rules! import_exception_type_object { /// ``` /// use pyo3::prelude::*; /// use pyo3::create_exception; -/// use pyo3::types::PyDict; +/// use pyo3::types::IntoPyDict; /// use pyo3::exceptions::Exception; /// /// create_exception!(mymodule, CustomError, Exception); @@ -141,9 +140,8 @@ macro_rules! import_exception_type_object { /// fn main() { /// let gil = Python::acquire_gil(); /// let py = gil.python(); -/// let ctx = PyDict::new(py); /// let error_type = py.get_type::(); -/// ctx.set_item("CustomError", error_type).unwrap(); +/// let ctx = [("CustomError", error_type)].into_py_dict(py); /// let type_description: String = py /// .eval("str(CustomError)", None, Some(&ctx)) /// .unwrap() @@ -381,7 +379,7 @@ pub mod socket { mod test { use crate::exceptions::Exception; use crate::objectprotocol::ObjectProtocol; - use crate::types::PyDict; + use crate::types::{PyDict, IntoPyDict}; use crate::{PyErr, Python}; import_exception!(socket, gaierror); @@ -445,9 +443,8 @@ mod test { let gil = Python::acquire_gil(); let py = gil.python(); - let ctx = PyDict::new(py); let error_type = py.get_type::(); - ctx.set_item("CustomError", error_type).unwrap(); + let ctx = [("CustomError", error_type)].into_py_dict(py); let type_description: String = py .eval("str(CustomError)", None, Some(&ctx)) .unwrap() @@ -457,7 +454,7 @@ mod test { py.run( "assert CustomError('oops').args == ('oops',)", None, - Some(ctx), + Some(&ctx), ) .unwrap(); } diff --git a/src/lib.rs b/src/lib.rs index 6c41745b..4f469b2a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -100,7 +100,7 @@ //! //! ```rust //! use pyo3::prelude::*; -//! use pyo3::types::PyDict; +//! use pyo3::types::IntoPyDict; //! //! fn main() -> PyResult<()> { //! let gil = Python::acquire_gil(); @@ -108,8 +108,7 @@ //! let sys = py.import("sys")?; //! let version: String = sys.get("version")?.extract()?; //! -//! let locals = PyDict::new(py); -//! locals.set_item("os", py.import("os")?)?; +//! let locals = [("os", py.import("os")?)].into_py_dict(py); //! let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'"; //! let user: String = py.eval(code, None, Some(&locals))?.extract()?; //! diff --git a/src/python.rs b/src/python.rs index 94c9d029..1ec9e8e2 100644 --- a/src/python.rs +++ b/src/python.rs @@ -390,7 +390,7 @@ impl<'p> Python<'p> { #[cfg(test)] mod test { use crate::objectprotocol::ObjectProtocol; - use crate::types::{PyAny, PyBool, PyDict, PyInt, PyList}; + use crate::types::{PyAny, PyBool, IntoPyDict, PyInt, PyList}; use crate::Python; #[test] @@ -407,8 +407,7 @@ mod test { .unwrap(); assert_eq!(v, 1); - let d = PyDict::new(py); - d.set_item("foo", 13).unwrap(); + let d = [("foo", 13)].into_py_dict(py); // Inject our own global namespace let v: i32 = py diff --git a/src/types/dict.rs b/src/types/dict.rs index b7fae879..b12543b9 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -314,8 +314,7 @@ mod test { fn test_new() { let gil = Python::acquire_gil(); let py = gil.python(); - let dict = PyDict::new(py); - dict.set_item(7, 32).unwrap(); + let dict = [(7, 32)].into_py_dict(py); assert_eq!(32, dict.get_item(7i32).unwrap().extract::().unwrap()); assert_eq!(None, dict.get_item(8i32)); } @@ -342,8 +341,7 @@ mod test { fn test_copy() { let gil = Python::acquire_gil(); let py = gil.python(); - let dict = PyDict::new(py); - dict.set_item(7, 32).unwrap(); + let dict = [(7, 32)].into_py_dict(py); let ndict = dict.copy().unwrap(); assert_eq!(32, ndict.get_item(7i32).unwrap().extract::().unwrap()); @@ -416,10 +414,9 @@ mod test { let cnt; { let _pool = crate::GILPool::new(); - let dict = PyDict::new(py); let none = py.None(); cnt = none.get_refcnt(); - dict.set_item(10, none).unwrap(); + let _dict = [(10, none)].into_py_dict(py); } { assert_eq!(cnt, py.None().get_refcnt()); diff --git a/tests/common.rs b/tests/common.rs index 01d0e704..193dfb02 100644 --- a/tests/common.rs +++ b/tests/common.rs @@ -24,8 +24,10 @@ pub fn indoc(commands: &str) -> String { #[macro_export] macro_rules! py_run { ($py:expr, $val:expr, $code:expr) => {{ - let d = pyo3::types::PyDict::new($py); - d.set_item(stringify!($val), &$val).unwrap(); + + use pyo3::types::IntoPyDict; + let d = [(stringify!($val), &$val)].into_py_dict($py); + $py.run(&common::indoc($code), None, Some(d)) .map_err(|e| { e.print($py); @@ -49,8 +51,10 @@ macro_rules! py_assert { #[macro_export] macro_rules! py_expect_exception { ($py:expr, $val:ident, $code:expr, $err:ident) => {{ - let d = pyo3::types::PyDict::new($py); - d.set_item(stringify!($val), &$val).unwrap(); + + use pyo3::types::IntoPyDict; + let d = [(stringify!($val), &$val)].into_py_dict($py); + let res = $py.run($code, None, Some(d)); let err = res.unwrap_err(); if !err.matches($py, $py.get_type::()) { diff --git a/tests/test_buffer_protocol.rs b/tests/test_buffer_protocol.rs index 9fcd0501..818bff0b 100644 --- a/tests/test_buffer_protocol.rs +++ b/tests/test_buffer_protocol.rs @@ -2,7 +2,7 @@ use pyo3::class::PyBufferProtocol; use pyo3::exceptions::BufferError; use pyo3::ffi; use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; use std::os::raw::{c_int, c_void}; use std::ptr; @@ -73,8 +73,7 @@ fn test_buffer() { ) .unwrap(); - let d = PyDict::new(py); - d.set_item("ob", t).unwrap(); + let d = [("ob", t)].into_py_dict(py); py.run("assert bytes(ob) == b' 23'", None, Some(d)).unwrap(); } @@ -92,8 +91,7 @@ fn test_buffer() { ) .unwrap(); - let d = PyDict::new(py); - d.set_item("ob", t).unwrap(); + let d = [("ob", t)].into_py_dict(py); py.run("assert memoryview(ob).tobytes() == ' 23'", None, Some(d)) .unwrap(); } diff --git a/tests/test_datetime.rs b/tests/test_datetime.rs index 5c738087..837a556e 100644 --- a/tests/test_datetime.rs +++ b/tests/test_datetime.rs @@ -2,7 +2,7 @@ use pyo3::ffi::*; use pyo3::prelude::*; -use pyo3::types::{PyAny, PyDict}; +use pyo3::types::{PyAny, IntoPyDict}; fn _get_subclasses<'p>( py: &'p Python, @@ -12,8 +12,7 @@ fn _get_subclasses<'p>( // Import the class from Python and create some subclasses let datetime = py.import("datetime")?; - let locals = PyDict::new(*py); - locals.set_item(py_type, datetime.get(py_type)?).unwrap(); + let locals = [(py_type, datetime.get(py_type)?)].into_py_dict(*py); let make_subclass_py = format!("class Subklass({}):\n pass", py_type); @@ -114,8 +113,7 @@ fn test_datetime_utc() { let dt = PyDateTime::new(py, 2018, 1, 1, 0, 0, 0, 0, Some(&utc)).unwrap(); - let locals = PyDict::new(py); - locals.set_item("dt", dt).unwrap(); + let locals = [("dt", dt)].into_py_dict(py); let offset: f32 = py .eval("dt.utcoffset().total_seconds()", None, Some(locals)) diff --git a/tests/test_dunder.rs b/tests/test_dunder.rs index c93fade4..d0ee329e 100644 --- a/tests/test_dunder.rs +++ b/tests/test_dunder.rs @@ -6,7 +6,7 @@ use pyo3::class::{ use pyo3::exceptions::{IndexError, ValueError}; use pyo3::ffi; use pyo3::prelude::*; -use pyo3::types::{PyAny, PyBytes, PyDict, PySlice, PyString, PyType}; +use pyo3::types::{PyAny, PyBytes, IntoPyDict, PySlice, PyString, PyType}; use pyo3::AsPyPointer; use std::{isize, iter}; @@ -427,8 +427,7 @@ fn test_cls_impl() { let py = gil.python(); let ob = Py::new(py, Test {}).unwrap(); - let d = PyDict::new(py); - d.set_item("ob", ob).unwrap(); + let d = [("ob", ob)].into_py_dict(py); py.run("assert ob[1] == 'int'", None, Some(d)).unwrap(); py.run("assert ob[100:200:1] == 'slice'", None, Some(d)) diff --git a/tests/test_inheritance.rs b/tests/test_inheritance.rs index afd44819..9f4f5e23 100644 --- a/tests/test_inheritance.rs +++ b/tests/test_inheritance.rs @@ -1,5 +1,5 @@ use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; use std::isize; #[macro_use] @@ -18,10 +18,8 @@ struct SubclassAble {} fn subclass() { let gil = Python::acquire_gil(); let py = gil.python(); + let d = [("SubclassAble", py.get_type::())].into_py_dict(py); - let d = PyDict::new(py); - d.set_item("SubclassAble", py.get_type::()) - .unwrap(); py.run( "class A(SubclassAble): pass\nassert issubclass(A, SubclassAble)", None, diff --git a/tests/test_methods.rs b/tests/test_methods.rs index 3cb01227..91ec3374 100644 --- a/tests/test_methods.rs +++ b/tests/test_methods.rs @@ -1,5 +1,5 @@ use pyo3::prelude::*; -use pyo3::types::{PyDict, PyString, PyTuple, PyType}; +use pyo3::types::{IntoPyDict, PyDict, PyString, PyTuple, PyType}; use pyo3::PyRawObject; #[macro_use] @@ -25,8 +25,7 @@ fn instance_method() { let obj = PyRefMut::new(py, InstanceMethod { member: 42 }).unwrap(); assert_eq!(obj.method().unwrap(), 42); - let d = PyDict::new(py); - d.set_item("obj", obj).unwrap(); + let d = [("obj", obj)].into_py_dict(py); py.run("assert obj.method() == 42", None, Some(d)).unwrap(); py.run("assert obj.method.__doc__ == 'Test method'", None, Some(d)) .unwrap(); @@ -52,8 +51,7 @@ fn instance_method_with_args() { let obj = PyRefMut::new(py, InstanceMethodWithArgs { member: 7 }).unwrap(); assert_eq!(obj.method(6).unwrap(), 42); - let d = PyDict::new(py); - d.set_item("obj", obj).unwrap(); + let d = [("obj", obj)].into_py_dict(py); py.run("assert obj.method(3) == 21", None, Some(d)).unwrap(); py.run("assert obj.method(multiplier=6) == 42", None, Some(d)) .unwrap(); @@ -80,8 +78,7 @@ fn class_method() { let gil = Python::acquire_gil(); let py = gil.python(); - let d = PyDict::new(py); - d.set_item("C", py.get_type::()).unwrap(); + let d = [("C", py.get_type::())].into_py_dict(py); py.run( "assert C.method() == 'ClassMethod.method()!'", None, @@ -112,9 +109,7 @@ fn class_method_with_args() { let gil = Python::acquire_gil(); let py = gil.python(); - let d = PyDict::new(py); - d.set_item("C", py.get_type::()) - .unwrap(); + let d = [("C", py.get_type::())].into_py_dict(py); py.run( "assert C.method('abc') == 'ClassMethodWithArgs.method(abc)'", None, @@ -145,8 +140,8 @@ fn static_method() { let py = gil.python(); assert_eq!(StaticMethod::method(py).unwrap(), "StaticMethod.method()!"); - let d = PyDict::new(py); - d.set_item("C", py.get_type::()).unwrap(); + + let d = [("C", py.get_type::())].into_py_dict(py); py.run( "assert C.method() == 'StaticMethod.method()!'", None, @@ -179,9 +174,7 @@ fn static_method_with_args() { assert_eq!(StaticMethodWithArgs::method(py, 1234).unwrap(), "0x4d2"); - let d = PyDict::new(py); - d.set_item("C", py.get_type::()) - .unwrap(); + let d = [("C", py.get_type::())].into_py_dict(py); py.run("assert C.method(1337) == '0x539'", None, Some(d)) .unwrap(); } diff --git a/tests/test_module.rs b/tests/test_module.rs index a4b54989..7bf2ce1f 100644 --- a/tests/test_module.rs +++ b/tests/test_module.rs @@ -1,7 +1,7 @@ use pyo3::prelude::*; #[cfg(Py_3)] -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; #[cfg(Py_3)] #[macro_use] @@ -58,12 +58,10 @@ fn test_module_with_functions() { let gil = Python::acquire_gil(); let py = gil.python(); - let d = PyDict::new(py); - d.set_item( + let d = [( "module_with_functions", wrap_pymodule!(module_with_functions)(py), - ) - .unwrap(); + )].into_py_dict(py); let run = |code| py.run(code, None, Some(d)).unwrap(); @@ -91,9 +89,7 @@ fn test_module_renaming() { let gil = Python::acquire_gil(); let py = gil.python(); - let d = PyDict::new(py); - d.set_item("different_name", wrap_pymodule!(other_name)(py)) - .unwrap(); + let d = [("different_name", wrap_pymodule!(other_name)(py))].into_py_dict(py); py.run( "assert different_name.__name__ == 'other_name'", diff --git a/tests/test_various.rs b/tests/test_various.rs index 03ea38a2..5af5792a 100644 --- a/tests/test_various.rs +++ b/tests/test_various.rs @@ -1,5 +1,5 @@ use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::IntoPyDict; use pyo3::types::PyTuple; use pyo3::wrap_pyfunction; use std::isize; @@ -30,9 +30,7 @@ fn mut_ref_arg() { let inst1 = Py::new(py, MutRefArg { n: 0 }).unwrap(); let inst2 = Py::new(py, MutRefArg { n: 0 }).unwrap(); - let d = PyDict::new(py); - d.set_item("inst1", &inst1).unwrap(); - d.set_item("inst2", &inst2).unwrap(); + let d = [("inst1", &inst1), ("inst2", &inst2)].into_py_dict(py); py.run("inst1.set_other(inst2)", None, Some(d)).unwrap(); assert_eq!(inst2.as_ref(py).n, 100);