Update tests & docs with IntoPyDict::into_py_dict(py)

This commit is contained in:
Miles Granger 2019-03-20 19:37:27 +01:00
parent 421b26bcef
commit 711155d7ad
17 changed files with 54 additions and 84 deletions

View File

@ -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);

View File

@ -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

View File

@ -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::<CustomError>()).unwrap();
let ctx = [("CustomError", py.get_type::<CustomError>())].into_py_dict(py);
py.run("assert str(CustomError) == \"<class 'mymodule.CustomError'>\"", None, Some(&ctx)).unwrap();
py.run("assert CustomError('oops').args == ('oops',)", None, Some(&ctx)).unwrap();

View File

@ -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);

View File

@ -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();
}

View File

@ -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::<gaierror>()).unwrap();
/// let ctx = [("gaierror", py.get_type::<gaierror>())].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::<CustomError>();
/// 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::<CustomError>();
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();
}

View File

@ -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()?;
//!

View File

@ -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

View File

@ -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::<i32>().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::<i32>().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());

View File

@ -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::<pyo3::exceptions::$err>()) {

View File

@ -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();
}

View File

@ -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))

View File

@ -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))

View File

@ -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::<SubclassAble>())].into_py_dict(py);
let d = PyDict::new(py);
d.set_item("SubclassAble", py.get_type::<SubclassAble>())
.unwrap();
py.run(
"class A(SubclassAble): pass\nassert issubclass(A, SubclassAble)",
None,

View File

@ -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::<ClassMethod>()).unwrap();
let d = [("C", py.get_type::<ClassMethod>())].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::<ClassMethodWithArgs>())
.unwrap();
let d = [("C", py.get_type::<ClassMethodWithArgs>())].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::<StaticMethod>()).unwrap();
let d = [("C", py.get_type::<StaticMethod>())].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::<StaticMethodWithArgs>())
.unwrap();
let d = [("C", py.get_type::<StaticMethodWithArgs>())].into_py_dict(py);
py.run("assert C.method(1337) == '0x539'", None, Some(d))
.unwrap();
}

View File

@ -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'",

View File

@ -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);