diff --git a/examples/maturin-starter/src/lib.rs b/examples/maturin-starter/src/lib.rs index faa147b2a10..4c2a30d3a5d 100644 --- a/examples/maturin-starter/src/lib.rs +++ b/examples/maturin-starter/src/lib.rs @@ -27,7 +27,7 @@ fn maturin_starter(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { // Inserting to sys.modules allows importing submodules nicely from Python // e.g. from maturin_starter.submodule import SubmoduleClass - let sys = PyModule::import_bound(py, "sys")?; + let sys = PyModule::import(py, "sys")?; let sys_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?; sys_modules.set_item("maturin_starter.submodule", m.getattr("submodule")?)?; diff --git a/examples/plugin/src/main.rs b/examples/plugin/src/main.rs index 5a54a1837cb..b50b54548e5 100644 --- a/examples/plugin/src/main.rs +++ b/examples/plugin/src/main.rs @@ -19,7 +19,7 @@ fn main() -> Result<(), Box> { // Now we can load our python_plugin/gadget_init_plugin.py file. // It can in turn import other stuff as it deems appropriate - let plugin = PyModule::import_bound(py, "gadget_init_plugin")?; + let plugin = PyModule::import(py, "gadget_init_plugin")?; // and call start function there, which will return a python reference to Gadget. // Gadget here is a "pyclass" object reference let gadget = plugin.getattr("start")?.call0()?; diff --git a/examples/setuptools-rust-starter/src/lib.rs b/examples/setuptools-rust-starter/src/lib.rs index d31284be7a3..a26623bc044 100644 --- a/examples/setuptools-rust-starter/src/lib.rs +++ b/examples/setuptools-rust-starter/src/lib.rs @@ -27,7 +27,7 @@ fn _setuptools_rust_starter(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult // Inserting to sys.modules allows importing submodules nicely from Python // e.g. from setuptools_rust_starter.submodule import SubmoduleClass - let sys = PyModule::import_bound(py, "sys")?; + let sys = PyModule::import(py, "sys")?; let sys_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?; sys_modules.set_item("setuptools_rust_starter.submodule", m.getattr("submodule")?)?; diff --git a/guide/src/class.md b/guide/src/class.md index 9f87f2828b0..02f8a2a194c 100644 --- a/guide/src/class.md +++ b/guide/src/class.md @@ -968,8 +968,8 @@ impl MyClass { # # fn main() -> PyResult<()> { # Python::with_gil(|py| { -# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?; -# let module = PyModule::new_bound(py, "my_module")?; +# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?; +# let module = PyModule::new(py, "my_module")?; # module.add_class::()?; # let class = module.getattr("MyClass")?; # diff --git a/guide/src/class/numeric.md b/guide/src/class/numeric.md index 541f8fb5893..adb2e46dbe3 100644 --- a/guide/src/class/numeric.md +++ b/guide/src/class/numeric.md @@ -386,7 +386,7 @@ fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> { # # fn main() -> PyResult<()> { # Python::with_gil(|py| -> PyResult<()> { -# let globals = PyModule::import_bound(py, "__main__")?.dict(); +# let globals = PyModule::import(py, "__main__")?.dict(); # globals.set_item("Number", Number::type_object_bound(py))?; # # py.run_bound(SCRIPT, Some(&globals), None)?; diff --git a/guide/src/conversions/traits.md b/guide/src/conversions/traits.md index 5e8c3fe4202..6836e0bd9fb 100644 --- a/guide/src/conversions/traits.md +++ b/guide/src/conversions/traits.md @@ -46,6 +46,7 @@ the Python object, i.e. `obj.getattr("my_string")`, and call `extract()` on the ```rust use pyo3::prelude::*; +use pyo3_ffi::c_str; #[derive(FromPyObject)] struct RustyStruct { @@ -54,13 +55,13 @@ struct RustyStruct { # # fn main() -> PyResult<()> { # Python::with_gil(|py| -> PyResult<()> { -# let module = PyModule::from_code_bound( +# let module = PyModule::from_code( # py, -# "class Foo: +# c_str!("class Foo: # def __init__(self): -# self.my_string = 'test'", -# "", -# "", +# self.my_string = 'test'"), +# c_str!(""), +# c_str!(""), # )?; # # let class = module.getattr("Foo")?; @@ -100,6 +101,7 @@ The argument passed to `getattr` and `get_item` can also be configured: ```rust use pyo3::prelude::*; +use pyo3_ffi::c_str; #[derive(FromPyObject)] struct RustyStruct { @@ -111,14 +113,14 @@ struct RustyStruct { # # fn main() -> PyResult<()> { # Python::with_gil(|py| -> PyResult<()> { -# let module = PyModule::from_code_bound( +# let module = PyModule::from_code( # py, -# "class Foo(dict): +# c_str!("class Foo(dict): # def __init__(self): # self.name = 'test' -# self['key'] = 'test2'", -# "", -# "", +# self['key'] = 'test2'"), +# c_str!(""), +# c_str!(""), # )?; # # let class = module.getattr("Foo")?; @@ -262,6 +264,7 @@ attribute can be applied to single-field-variants. ```rust use pyo3::prelude::*; +use pyo3_ffi::c_str; #[derive(FromPyObject)] # #[derive(Debug)] @@ -339,15 +342,15 @@ enum RustyEnum<'py> { # ); # } # { -# let module = PyModule::from_code_bound( +# let module = PyModule::from_code( # py, -# "class Foo(dict): +# c_str!("class Foo(dict): # def __init__(self): # self.x = 0 # self.y = 1 -# self.z = 2", -# "", -# "", +# self.z = 2"), +# c_str!(""), +# c_str!(""), # )?; # # let class = module.getattr("Foo")?; @@ -364,14 +367,14 @@ enum RustyEnum<'py> { # } # # { -# let module = PyModule::from_code_bound( +# let module = PyModule::from_code( # py, -# "class Foo(dict): +# c_str!("class Foo(dict): # def __init__(self): # self.x = 3 -# self.y = 4", -# "", -# "", +# self.y = 4"), +# c_str!(""), +# c_str!(""), # )?; # # let class = module.getattr("Foo")?; diff --git a/guide/src/function/signature.md b/guide/src/function/signature.md index 0b3d7a9a507..8ebe74456a1 100644 --- a/guide/src/function/signature.md +++ b/guide/src/function/signature.md @@ -150,7 +150,7 @@ fn increment(x: u64, amount: Option) -> u64 { # Python::with_gil(|py| { # let fun = pyo3::wrap_pyfunction!(increment, py)?; # -# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?; +# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?; # let sig: String = inspect # .call1((fun,))? # .call_method0("__str__")? @@ -178,7 +178,7 @@ fn increment(x: u64, amount: Option) -> u64 { # Python::with_gil(|py| { # let fun = pyo3::wrap_pyfunction!(increment, py)?; # -# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?; +# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?; # let sig: String = inspect # .call1((fun,))? # .call_method0("__str__")? @@ -221,7 +221,7 @@ fn add(a: u64, b: u64) -> u64 { # let doc: String = fun.getattr("__doc__")?.extract()?; # assert_eq!(doc, "This function adds two unsigned 64-bit integers."); # -# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?; +# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?; # let sig: String = inspect # .call1((fun,))? # .call_method0("__str__")? @@ -269,7 +269,7 @@ fn add(a: u64, b: u64) -> u64 { # let doc: String = fun.getattr("__doc__")?.extract()?; # assert_eq!(doc, "This function adds two unsigned 64-bit integers."); # -# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?; +# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?; # let sig: String = inspect # .call1((fun,))? # .call_method0("__str__")? diff --git a/guide/src/module.md b/guide/src/module.md index c6a7b3c9c64..4aac2937016 100644 --- a/guide/src/module.md +++ b/guide/src/module.md @@ -75,7 +75,7 @@ fn parent_module(m: &Bound<'_, PyModule>) -> PyResult<()> { } fn register_child_module(parent_module: &Bound<'_, PyModule>) -> PyResult<()> { - let child_module = PyModule::new_bound(parent_module.py(), "child_module")?; + let child_module = PyModule::new(parent_module.py(), "child_module")?; child_module.add_function(wrap_pyfunction!(func, &child_module)?)?; parent_module.add_submodule(&child_module) } diff --git a/guide/src/python-from-rust/calling-existing-code.md b/guide/src/python-from-rust/calling-existing-code.md index 997009310b4..0378bbf4611 100644 --- a/guide/src/python-from-rust/calling-existing-code.md +++ b/guide/src/python-from-rust/calling-existing-code.md @@ -2,9 +2,9 @@ If you already have some existing Python code that you need to execute from Rust, the following FAQs can help you select the right PyO3 functionality for your situation: -## Want to access Python APIs? Then use `PyModule::import_bound`. +## Want to access Python APIs? Then use `PyModule::import`. -[`PyModule::import_bound`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.import_bound) can +[`PyModule::import`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.import) can be used to get handle to a Python module from Rust. You can use this to import and use any Python module available in your environment. @@ -13,7 +13,7 @@ use pyo3::prelude::*; fn main() -> PyResult<()> { Python::with_gil(|py| { - let builtins = PyModule::import_bound(py, "builtins")?; + let builtins = PyModule::import(py, "builtins")?; let total: i32 = builtins .getattr("sum")? .call1((vec![1, 2, 3],))? @@ -95,9 +95,9 @@ assert userdata.as_tuple() == userdata_as_tuple # } ``` -## You have a Python file or code snippet? Then use `PyModule::from_code_bound`. +## You have a Python file or code snippet? Then use `PyModule::from_code`. -[`PyModule::from_code_bound`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.from_code_bound) +[`PyModule::from_code`]({{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.from_code) can be used to generate a Python module which can then be used just as if it was imported with `PyModule::import`. @@ -106,21 +106,22 @@ to this function! ```rust use pyo3::{prelude::*, types::IntoPyDict}; +use pyo3_ffi::c_str; # fn main() -> PyResult<()> { Python::with_gil(|py| { - let activators = PyModule::from_code_bound( + let activators = PyModule::from_code( py, - r#" + c_str!(r#" def relu(x): """see https://en.wikipedia.org/wiki/Rectifier_(neural_networks)""" return max(0.0, x) def leaky_relu(x, slope=0.01): return x if x >= 0 else x * slope - "#, - "activators.py", - "activators", + "#), + c_str!("activators.py"), + c_str!("activators"), )?; let relu_result: f64 = activators.getattr("relu")?.call1((-1.0,))?.extract()?; @@ -171,7 +172,7 @@ fn main() -> PyResult<()> { ``` If `append_to_inittab` cannot be used due to constraints in the program, -an alternative is to create a module using [`PyModule::new_bound`] +an alternative is to create a module using [`PyModule::new`] and insert it manually into `sys.modules`: ```rust @@ -186,11 +187,11 @@ pub fn add_one(x: i64) -> i64 { fn main() -> PyResult<()> { Python::with_gil(|py| { // Create new module - let foo_module = PyModule::new_bound(py, "foo")?; + let foo_module = PyModule::new(py, "foo")?; foo_module.add_function(wrap_pyfunction!(add_one, &foo_module)?)?; // Import and get sys.modules - let sys = PyModule::import_bound(py, "sys")?; + let sys = PyModule::import(py, "sys")?; let py_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?; // Insert foo into sys.modules @@ -249,16 +250,17 @@ The example below shows: `src/main.rs`: ```rust,ignore use pyo3::prelude::*; +use pyo3_ffi::c_str; fn main() -> PyResult<()> { - let py_foo = include_str!(concat!( + let py_foo = c_str!(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/python_app/utils/foo.py" - )); - let py_app = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python_app/app.py")); + ))); + let py_app = c_str!(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python_app/app.py"))); let from_python = Python::with_gil(|py| -> PyResult> { - PyModule::from_code_bound(py, py_foo, "utils.foo", "utils.foo")?; - let app: Py = PyModule::from_code_bound(py, py_app, "", "")? + PyModule::from_code(py, py_foo, c_str!("utils.foo"), c_str!("utils.foo"))?; + let app: Py = PyModule::from_code(py, py_app, c_str!(""), c_str!(""))? .getattr("run")? .into(); app.call0(py) @@ -283,19 +285,21 @@ that directory is `/usr/share/python_app`). ```rust,no_run use pyo3::prelude::*; use pyo3::types::PyList; +use pyo3_ffi::c_str; use std::fs; use std::path::Path; +use std::ffi::CString; fn main() -> PyResult<()> { let path = Path::new("/usr/share/python_app"); - let py_app = fs::read_to_string(path.join("app.py"))?; + let py_app = CString::new(fs::read_to_string(path.join("app.py"))?)?; let from_python = Python::with_gil(|py| -> PyResult> { let syspath = py .import("sys")? .getattr("path")? .downcast_into::()?; syspath.insert(0, &path)?; - let app: Py = PyModule::from_code_bound(py, &py_app, "", "")? + let app: Py = PyModule::from_code(py, py_app.as_c_str(), c_str!(""), c_str!(""))? .getattr("run")? .into(); app.call0(py) @@ -316,12 +320,13 @@ Use context managers by directly invoking `__enter__` and `__exit__`. ```rust use pyo3::prelude::*; +use pyo3_ffi::c_str; fn main() { Python::with_gil(|py| { - let custom_manager = PyModule::from_code_bound( + let custom_manager = PyModule::from_code( py, - r#" + c_str!(r#" class House(object): def __init__(self, address): self.address = address @@ -333,9 +338,9 @@ class House(object): else: print(f"Thank you for visiting {self.address}, come again soon!") - "#, - "house.py", - "house", + "#), + c_str!("house.py"), + c_str!("house"), ) .unwrap(); @@ -394,4 +399,4 @@ Python::with_gil(|py| -> PyResult<()> { ``` -[`PyModule::new_bound`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.new_bound +[`PyModule::new`]: {{#PYO3_DOCS_URL}}/pyo3/types/struct.PyModule.html#method.new diff --git a/guide/src/python-from-rust/function-calls.md b/guide/src/python-from-rust/function-calls.md index 3f27b7d2da5..22fcd8cacf0 100644 --- a/guide/src/python-from-rust/function-calls.md +++ b/guide/src/python-from-rust/function-calls.md @@ -19,6 +19,7 @@ The example below calls a Python function behind a `PyObject` (aka `Py`) ```rust use pyo3::prelude::*; use pyo3::types::PyTuple; +use pyo3_ffi::c_str; fn main() -> PyResult<()> { let arg1 = "arg1"; @@ -26,17 +27,17 @@ fn main() -> PyResult<()> { let arg3 = "arg3"; Python::with_gil(|py| { - let fun: Py = PyModule::from_code_bound( + let fun: Py = PyModule::from_code( py, - "def example(*args, **kwargs): + c_str!("def example(*args, **kwargs): if args != (): print('called with args', args) if kwargs != {}: print('called with kwargs', kwargs) if args == () and kwargs == {}: - print('called with no arguments')", - "", - "", + print('called with no arguments')"), + c_str!(""), + c_str!(""), )? .getattr("example")? .into(); @@ -64,6 +65,7 @@ For the `call` and `call_method` APIs, `kwargs` are `Option<&Bound<'py, PyDict>> use pyo3::prelude::*; use pyo3::types::IntoPyDict; use std::collections::HashMap; +use pyo3_ffi::c_str; fn main() -> PyResult<()> { let key1 = "key1"; @@ -72,17 +74,17 @@ fn main() -> PyResult<()> { let val2 = 2; Python::with_gil(|py| { - let fun: Py = PyModule::from_code_bound( + let fun: Py = PyModule::from_code( py, - "def example(*args, **kwargs): + c_str!("def example(*args, **kwargs): if args != (): print('called with args', args) if kwargs != {}: print('called with kwargs', kwargs) if args == () and kwargs == {}: - print('called with no arguments')", - "", - "", + print('called with no arguments')"), + c_str!(""), + c_str!(""), )? .getattr("example")? .into(); diff --git a/newsfragments/4404.changed.md b/newsfragments/4404.changed.md new file mode 100644 index 00000000000..728c45ae694 --- /dev/null +++ b/newsfragments/4404.changed.md @@ -0,0 +1 @@ +`PyModule::from_code` now expects &CStr as arguments instead of `&str`. \ No newline at end of file diff --git a/pyo3-benches/benches/bench_call.rs b/pyo3-benches/benches/bench_call.rs index 8470c8768d3..ca18bbd5e60 100644 --- a/pyo3-benches/benches/bench_call.rs +++ b/pyo3-benches/benches/bench_call.rs @@ -3,10 +3,11 @@ use std::hint::black_box; use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion}; use pyo3::prelude::*; +use pyo3::ffi::c_str; macro_rules! test_module { ($py:ident, $code:literal) => { - PyModule::from_code_bound($py, $code, file!(), "test_module") + PyModule::from_code($py, c_str!($code), c_str!(file!()), c_str!("test_module")) .expect("module creation failed") }; } diff --git a/pyo3-ffi/src/moduleobject.rs b/pyo3-ffi/src/moduleobject.rs index b9026997d2e..04b0f4ac25f 100644 --- a/pyo3-ffi/src/moduleobject.rs +++ b/pyo3-ffi/src/moduleobject.rs @@ -21,6 +21,7 @@ pub unsafe fn PyModule_CheckExact(op: *mut PyObject) -> c_int { } extern "C" { + #[cfg_attr(PyPy, link_name = "PyPyModule_NewObject")] pub fn PyModule_NewObject(name: *mut PyObject) -> *mut PyObject; #[cfg_attr(PyPy, link_name = "PyPyModule_New")] pub fn PyModule_New(name: *const c_char) -> *mut PyObject; diff --git a/pytests/src/lib.rs b/pytests/src/lib.rs index cbd65c8012c..72f5feaa0f4 100644 --- a/pytests/src/lib.rs +++ b/pytests/src/lib.rs @@ -39,7 +39,7 @@ fn pyo3_pytests(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { // Inserting to sys.modules allows importing submodules nicely from Python // e.g. import pyo3_pytests.buf_and_str as bas - let sys = PyModule::import_bound(py, "sys")?; + let sys = PyModule::import(py, "sys")?; let sys_modules = sys.getattr("modules")?.downcast_into::()?; sys_modules.set_item("pyo3_pytests.awaitable", m.getattr("awaitable")?)?; sys_modules.set_item("pyo3_pytests.buf_and_str", m.getattr("buf_and_str")?)?; diff --git a/src/conversions/anyhow.rs b/src/conversions/anyhow.rs index 4167c5379e1..c5614b7159c 100644 --- a/src/conversions/anyhow.rs +++ b/src/conversions/anyhow.rs @@ -74,7 +74,7 @@ //! // could call inside an application... //! // This might return a `PyErr`. //! let res = Python::with_gil(|py| { -//! let zlib = PyModule::import_bound(py, "zlib")?; +//! let zlib = PyModule::import(py, "zlib")?; //! let decompress = zlib.getattr("decompress")?; //! let bytes = PyBytes::new(py, bytes); //! let value = decompress.call1((bytes,))?; diff --git a/src/conversions/eyre.rs b/src/conversions/eyre.rs index 87894783d27..23cb43a5a5b 100644 --- a/src/conversions/eyre.rs +++ b/src/conversions/eyre.rs @@ -73,7 +73,7 @@ //! // could call inside an application... //! // This might return a `PyErr`. //! let res = Python::with_gil(|py| { -//! let zlib = PyModule::import_bound(py, "zlib")?; +//! let zlib = PyModule::import(py, "zlib")?; //! let decompress = zlib.getattr("decompress")?; //! let bytes = PyBytes::new(py, bytes); //! let value = decompress.call1((bytes,))?; diff --git a/src/conversions/num_bigint.rs b/src/conversions/num_bigint.rs index d709824d702..a0c986f047b 100644 --- a/src/conversions/num_bigint.rs +++ b/src/conversions/num_bigint.rs @@ -381,6 +381,7 @@ mod tests { use super::*; use crate::types::{PyDict, PyModule}; use indoc::indoc; + use pyo3_ffi::c_str; fn rust_fib() -> impl Iterator where @@ -441,7 +442,7 @@ mod tests { } fn python_index_class(py: Python<'_>) -> Bound<'_, PyModule> { - let index_code = indoc!( + let index_code = c_str!(indoc!( r#" class C: def __init__(self, x): @@ -449,8 +450,8 @@ mod tests { def __index__(self): return self.x "# - ); - PyModule::from_code_bound(py, index_code, "index.py", "index").unwrap() + )); + PyModule::from_code(py, index_code, c_str!("index.py"), c_str!("index")).unwrap() } #[test] diff --git a/src/conversions/num_complex.rs b/src/conversions/num_complex.rs index 0b2e714b995..645d704c672 100644 --- a/src/conversions/num_complex.rs +++ b/src/conversions/num_complex.rs @@ -55,7 +55,7 @@ //! # //! # fn main() -> PyResult<()> { //! # Python::with_gil(|py| -> PyResult<()> { -//! # let module = PyModule::new_bound(py, "my_module")?; +//! # let module = PyModule::new(py, "my_module")?; //! # //! # module.add_function(&wrap_pyfunction!(get_eigenvalues, module)?)?; //! # @@ -205,6 +205,7 @@ complex_conversion!(f64); mod tests { use super::*; use crate::types::{complex::PyComplexMethods, PyModule}; + use pyo3_ffi::c_str; #[test] fn from_complex() { @@ -233,18 +234,20 @@ mod tests { #[test] fn from_python_magic() { Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class A: def __complex__(self): return 3.0+1.2j class B: def __float__(self): return 3.0 class C: def __index__(self): return 3 - "#, - "test.py", - "test", + "# + ), + c_str!("test.py"), + c_str!("test"), ) .unwrap(); let from_complex = module.getattr("A").unwrap().call0().unwrap(); @@ -271,9 +274,10 @@ class C: #[test] fn from_python_inherited_magic() { Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class First: pass class ComplexMixin: def __complex__(self): return 3.0+1.2j @@ -284,9 +288,10 @@ class IndexMixin: class A(First, ComplexMixin): pass class B(First, FloatMixin): pass class C(First, IndexMixin): pass - "#, - "test.py", - "test", + "# + ), + c_str!("test.py"), + c_str!("test"), ) .unwrap(); let from_complex = module.getattr("A").unwrap().call0().unwrap(); @@ -315,16 +320,18 @@ class C(First, IndexMixin): pass // `type(inst).attr(inst)` equivalent to `inst.attr()` for methods, but this isn't the only // way the descriptor protocol might be implemented. Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class A: @property def __complex__(self): return lambda: 3.0+1.2j - "#, - "test.py", - "test", + "# + ), + c_str!("test.py"), + c_str!("test"), ) .unwrap(); let obj = module.getattr("A").unwrap().call0().unwrap(); @@ -338,16 +345,18 @@ class A: fn from_python_nondescriptor_magic() { // Magic methods don't need to implement the descriptor protocol, if they're callable. Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class MyComplex: def __call__(self): return 3.0+1.2j class A: __complex__ = MyComplex() - "#, - "test.py", - "test", + "# + ), + c_str!("test.py"), + c_str!("test"), ) .unwrap(); let obj = module.getattr("A").unwrap().call0().unwrap(); diff --git a/src/instance.rs b/src/instance.rs index 773431859c9..d49a1f4d6f4 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -923,7 +923,7 @@ impl<'a, 'py, T> BoundObject<'py, T> for Borrowed<'a, 'py, T> { /// # /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| { -/// # let m = pyo3::types::PyModule::new_bound(py, "test")?; +/// # let m = pyo3::types::PyModule::new(py, "test")?; /// # m.add_class::()?; /// # /// # let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?; @@ -960,7 +960,7 @@ impl<'a, 'py, T> BoundObject<'py, T> for Borrowed<'a, 'py, T> { /// # /// # fn main() -> PyResult<()> { /// # Python::with_gil(|py| { -/// # let m = pyo3::types::PyModule::new_bound(py, "test")?; +/// # let m = pyo3::types::PyModule::new(py, "test")?; /// # m.add_class::()?; /// # /// # let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?; @@ -1451,7 +1451,7 @@ impl Py { /// } /// # /// # Python::with_gil(|py| { - /// # let ob = PyModule::new_bound(py, "empty").unwrap().into_py(py); + /// # let ob = PyModule::new(py, "empty").unwrap().into_py(py); /// # set_answer(ob, py).unwrap(); /// # }); /// ``` @@ -1902,6 +1902,8 @@ mod tests { use super::{Bound, Py, PyObject}; use crate::types::{dict::IntoPyDict, PyAnyMethods, PyCapsule, PyDict, PyString}; use crate::{ffi, Borrowed, PyAny, PyResult, Python, ToPyObject}; + use pyo3_ffi::c_str; + use std::ffi::CStr; #[test] fn test_call() { @@ -1966,12 +1968,14 @@ mod tests { use crate::types::PyModule; Python::with_gil(|py| { - const CODE: &str = r#" + const CODE: &CStr = c_str!( + r#" class A: pass a = A() - "#; - let module = PyModule::from_code_bound(py, CODE, "", "")?; + "# + ); + let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; let instance: Py = module.getattr("a")?.into(); instance.getattr(py, "foo").unwrap_err(); @@ -1993,12 +1997,14 @@ a = A() use crate::types::PyModule; Python::with_gil(|py| { - const CODE: &str = r#" + const CODE: &CStr = c_str!( + r#" class A: pass a = A() - "#; - let module = PyModule::from_code_bound(py, CODE, "", "")?; + "# + ); + let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; let instance: Py = module.getattr("a")?.into(); let foo = crate::intern!(py, "foo"); diff --git a/src/marker.rs b/src/marker.rs index 778ccf61c7d..37a48b2ec23 100644 --- a/src/marker.rs +++ b/src/marker.rs @@ -350,7 +350,7 @@ pub use nightly::Ungil; /// # Releasing and freeing memory /// /// The [`Python<'py>`] type can be used to create references to variables owned by the Python -/// interpreter, using functions such as [`Python::eval_bound`] and [`PyModule::import_bound`]. +/// interpreter, using functions such as [`Python::eval_bound`] and [`PyModule::import`]. #[derive(Copy, Clone)] pub struct Python<'py>(PhantomData<(&'py GILGuard, NotSend)>); @@ -674,7 +674,7 @@ impl<'py> Python<'py> { where N: IntoPy>, { - PyModule::import_bound(self, name) + PyModule::import(self, name) } /// Deprecated name for [`Python::import`]. diff --git a/src/pyclass_init.rs b/src/pyclass_init.rs index 28b4a1cd719..01983c79b13 100644 --- a/src/pyclass_init.rs +++ b/src/pyclass_init.rs @@ -183,7 +183,7 @@ impl PyClassInitializer { /// /// fn main() -> PyResult<()> { /// Python::with_gil(|py| { - /// let m = PyModule::new_bound(py, "example")?; + /// let m = PyModule::new(py, "example")?; /// m.add_class::()?; /// m.add_class::()?; /// diff --git a/src/types/any.rs b/src/types/any.rs index d3322d1c33f..06493e437c3 100644 --- a/src/types/any.rs +++ b/src/types/any.rs @@ -127,7 +127,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// } /// # /// # Python::with_gil(|py| { - /// # let ob = PyModule::new_bound(py, "empty").unwrap(); + /// # let ob = PyModule::new(py, "empty").unwrap(); /// # set_answer(&ob).unwrap(); /// # }); /// ``` @@ -377,7 +377,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { - /// let builtins = PyModule::import_bound(py, "builtins")?; + /// let builtins = PyModule::import(py, "builtins")?; /// let print = builtins.getattr("print")?; /// assert!(print.is_callable()); /// Ok(()) @@ -404,17 +404,19 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; + /// use pyo3_ffi::c_str; + /// use std::ffi::CStr; /// - /// const CODE: &str = r#" + /// const CODE: &CStr = c_str!(r#" /// def function(*args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {"cruel": "world"} /// return "called with args and kwargs" - /// "#; + /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { - /// let module = PyModule::from_code_bound(py, CODE, "", "")?; + /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let fun = module.getattr("function")?; /// let args = ("hello",); /// let kwargs = PyDict::new(py); @@ -442,7 +444,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { - /// let module = PyModule::import_bound(py, "builtins")?; + /// let module = PyModule::import(py, "builtins")?; /// let help = module.getattr("help")?; /// help.call0()?; /// Ok(()) @@ -461,17 +463,19 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// /// ```rust /// use pyo3::prelude::*; + /// use pyo3_ffi::c_str; + /// use std::ffi::CStr; /// - /// const CODE: &str = r#" + /// const CODE: &CStr = c_str!(r#" /// def function(*args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {} /// return "called with args" - /// "#; + /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { - /// let module = PyModule::from_code_bound(py, CODE, "", "")?; + /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let fun = module.getattr("function")?; /// let args = ("hello",); /// let result = fun.call1(args)?; @@ -494,19 +498,21 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// ```rust /// use pyo3::prelude::*; /// use pyo3::types::PyDict; + /// use pyo3_ffi::c_str; + /// use std::ffi::CStr; /// - /// const CODE: &str = r#" + /// const CODE: &CStr = c_str!(r#" /// class A: /// def method(self, *args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {"cruel": "world"} /// return "called with args and kwargs" /// a = A() - /// "#; + /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { - /// let module = PyModule::from_code_bound(py, CODE, "", "")?; + /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let instance = module.getattr("a")?; /// let args = ("hello",); /// let kwargs = PyDict::new(py); @@ -538,19 +544,21 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// /// ```rust /// use pyo3::prelude::*; + /// use pyo3_ffi::c_str; + /// use std::ffi::CStr; /// - /// const CODE: &str = r#" + /// const CODE: &CStr = c_str!(r#" /// class A: /// def method(self, *args, **kwargs): /// assert args == () /// assert kwargs == {} /// return "called with no arguments" /// a = A() - /// "#; + /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { - /// let module = PyModule::from_code_bound(py, CODE, "", "")?; + /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let instance = module.getattr("a")?; /// let result = instance.call_method0("method")?; /// assert_eq!(result.extract::()?, "called with no arguments"); @@ -573,19 +581,21 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed { /// /// ```rust /// use pyo3::prelude::*; + /// use pyo3_ffi::c_str; + /// use std::ffi::CStr; /// - /// const CODE: &str = r#" + /// const CODE: &CStr = c_str!(r#" /// class A: /// def method(self, *args, **kwargs): /// assert args == ("hello",) /// assert kwargs == {} /// return "called with args" /// a = A() - /// "#; + /// "#); /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| { - /// let module = PyModule::from_code_bound(py, CODE, "", "")?; + /// let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?; /// let instance = module.getattr("a")?; /// let args = ("hello",); /// let result = instance.call_method1("method", args)?; @@ -1528,13 +1538,15 @@ mod tests { types::{IntoPyDict, PyAny, PyAnyMethods, PyBool, PyInt, PyList, PyModule, PyTypeMethods}, Bound, PyTypeInfo, Python, ToPyObject, }; + use pyo3_ffi::c_str; #[test] fn test_lookup_special() { Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class CustomCallable: def __call__(self): return 1 @@ -1564,9 +1576,10 @@ class ErrorInDescriptorInt: class NonHeapNonDescriptorInt: # A static-typed callable that doesn't implement `__get__`. These are pretty hard to come by. __int__ = int - "#, - "test.py", - "test", + "# + ), + c_str!("test.py"), + c_str!("test"), ) .unwrap(); @@ -1625,15 +1638,17 @@ class NonHeapNonDescriptorInt: #[test] fn test_call_method0() { Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class SimpleClass: def foo(self): return 42 -"#, - file!(), - "test_module", +"# + ), + c_str!(file!()), + c_str!("test_module"), ) .expect("module creation failed"); diff --git a/src/types/capsule.rs b/src/types/capsule.rs index 83ce85faf47..a6a2ba30c7b 100644 --- a/src/types/capsule.rs +++ b/src/types/capsule.rs @@ -35,7 +35,7 @@ use std::os::raw::{c_char, c_int, c_void}; /// /// let capsule = PyCapsule::new(py, foo, Some(name.clone()))?; /// -/// let module = PyModule::import_bound(py, "builtins")?; +/// let module = PyModule::import(py, "builtins")?; /// module.add("capsule", capsule)?; /// /// let cap: &Foo = unsafe { PyCapsule::import(py, name.as_ref())? }; @@ -444,7 +444,7 @@ mod tests { let capsule = PyCapsule::new(py, foo, Some(name.clone()))?; - let module = PyModule::import_bound(py, "builtins")?; + let module = PyModule::import(py, "builtins")?; module.add("capsule", capsule)?; // check error when wrong named passed for capsule. diff --git a/src/types/module.rs b/src/types/module.rs index 873d3347fc0..7307dfd4c2d 100644 --- a/src/types/module.rs +++ b/src/types/module.rs @@ -7,7 +7,7 @@ use crate::types::{ any::PyAnyMethods, list::PyListMethods, PyAny, PyCFunction, PyDict, PyList, PyString, }; use crate::{exceptions, ffi, Bound, IntoPy, Py, PyObject, Python}; -use std::ffi::CString; +use std::ffi::{CStr, CString}; use std::str; /// Represents a Python [`module`][1] object. @@ -38,23 +38,29 @@ impl PyModule { /// /// # fn main() -> PyResult<()> { /// Python::with_gil(|py| -> PyResult<()> { - /// let module = PyModule::new_bound(py, "my_module")?; + /// let module = PyModule::new(py, "my_module")?; /// /// assert_eq!(module.name()?, "my_module"); /// Ok(()) /// })?; /// # Ok(())} /// ``` - pub fn new_bound<'py>(py: Python<'py>, name: &str) -> PyResult> { - // Could use PyModule_NewObject, but it doesn't exist on PyPy. - let name = CString::new(name)?; + pub fn new<'py>(py: Python<'py>, name: &str) -> PyResult> { + let name = PyString::new(py, name); unsafe { - ffi::PyModule_New(name.as_ptr()) + ffi::PyModule_NewObject(name.as_ptr()) .assume_owned_or_err(py) .downcast_into_unchecked() } } + /// Deprecated name for [`PyModule::new`]. + #[deprecated(since = "0.23.0", note = "renamed to `PyModule::new`")] + #[inline] + pub fn new_bound<'py>(py: Python<'py>, name: &str) -> PyResult> { + Self::new(py, name) + } + /// Imports the Python module with the specified name. /// /// # Examples @@ -64,7 +70,7 @@ impl PyModule { /// use pyo3::prelude::*; /// /// Python::with_gil(|py| { - /// let module = PyModule::import_bound(py, "antigravity").expect("No flying for you."); + /// let module = PyModule::import(py, "antigravity").expect("No flying for you."); /// }); /// # } /// ``` @@ -73,7 +79,7 @@ impl PyModule { /// ```python /// import antigravity /// ``` - pub fn import_bound(py: Python<'_>, name: N) -> PyResult> + pub fn import(py: Python<'_>, name: N) -> PyResult> where N: IntoPy>, { @@ -85,6 +91,16 @@ impl PyModule { } } + /// Deprecated name for [`PyModule::import`]. + #[deprecated(since = "0.23.0", note = "renamed to `PyModule::import`")] + #[inline] + pub fn import_bound(py: Python<'_>, name: N) -> PyResult> + where + N: IntoPy>, + { + Self::import(py, name) + } + /// Creates and loads a module named `module_name`, /// containing the Python code passed to `code` /// and pretending to live at `file_name`. @@ -108,13 +124,14 @@ impl PyModule { /// /// ```rust /// use pyo3::prelude::*; + /// use pyo3::ffi::c_str; /// /// # fn main() -> PyResult<()> { /// // This path is resolved relative to this file. - /// let code = include_str!("../../assets/script.py"); + /// let code = c_str!(include_str!("../../assets/script.py")); /// /// Python::with_gil(|py| -> PyResult<()> { - /// PyModule::from_code_bound(py, code, "example.py", "example")?; + /// PyModule::from_code(py, code, c_str!("example.py"), c_str!("example"))?; /// Ok(()) /// })?; /// # Ok(()) @@ -125,6 +142,8 @@ impl PyModule { /// /// ```rust /// use pyo3::prelude::*; + /// use pyo3::ffi::c_str; + /// use std::ffi::CString; /// /// # fn main() -> PyResult<()> { /// // This path is resolved by however the platform resolves paths, @@ -133,12 +152,31 @@ impl PyModule { /// let code = std::fs::read_to_string("assets/script.py")?; /// /// Python::with_gil(|py| -> PyResult<()> { - /// PyModule::from_code_bound(py, &code, "example.py", "example")?; + /// PyModule::from_code(py, CString::new(code)?.as_c_str(), c_str!("example.py"), c_str!("example"))?; /// Ok(()) /// })?; /// Ok(()) /// # } /// ``` + pub fn from_code<'py>( + py: Python<'py>, + code: &CStr, + file_name: &CStr, + module_name: &CStr, + ) -> PyResult> { + unsafe { + let code = ffi::Py_CompileString(code.as_ptr(), file_name.as_ptr(), ffi::Py_file_input) + .assume_owned_or_err(py)?; + + ffi::PyImport_ExecCodeModuleEx(module_name.as_ptr(), code.as_ptr(), file_name.as_ptr()) + .assume_owned_or_err(py) + .downcast_into() + } + } + + /// Deprecated name for [`PyModule::from_code`]. + #[deprecated(since = "0.23.0", note = "renamed to `PyModule::from_code`")] + #[inline] pub fn from_code_bound<'py>( py: Python<'py>, code: &str, @@ -149,14 +187,7 @@ impl PyModule { let filename = CString::new(file_name)?; let module = CString::new(module_name)?; - unsafe { - let code = ffi::Py_CompileString(data.as_ptr(), filename.as_ptr(), ffi::Py_file_input) - .assume_owned_or_err(py)?; - - ffi::PyImport_ExecCodeModuleEx(module.as_ptr(), code.as_ptr(), filename.as_ptr()) - .assume_owned_or_err(py) - .downcast_into() - } + Self::from_code(py, data.as_c_str(), filename.as_c_str(), module.as_c_str()) } } @@ -288,7 +319,7 @@ pub trait PyModuleMethods<'py>: crate::sealed::Sealed { /// /// #[pymodule] /// fn my_module(py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> { - /// let submodule = PyModule::new_bound(py, "submodule")?; + /// let submodule = PyModule::new(py, "submodule")?; /// submodule.add("super_useful_constant", "important")?; /// /// module.add_submodule(&submodule)?; @@ -491,7 +522,7 @@ mod tests { #[test] fn module_import_and_name() { Python::with_gil(|py| { - let builtins = PyModule::import_bound(py, "builtins").unwrap(); + let builtins = PyModule::import(py, "builtins").unwrap(); assert_eq!(builtins.name().unwrap(), "builtins"); }) } @@ -500,7 +531,7 @@ mod tests { fn module_filename() { use crate::types::string::PyStringMethods; Python::with_gil(|py| { - let site = PyModule::import_bound(py, "site").unwrap(); + let site = PyModule::import(py, "site").unwrap(); assert!(site .filename() .unwrap() diff --git a/src/types/typeobject.rs b/src/types/typeobject.rs index 0c3b0a6aaa5..1d05015b591 100644 --- a/src/types/typeobject.rs +++ b/src/types/typeobject.rs @@ -253,6 +253,7 @@ mod tests { use crate::types::{PyAnyMethods, PyBool, PyInt, PyModule, PyTuple, PyType, PyTypeMethods}; use crate::PyAny; use crate::Python; + use pyo3_ffi::c_str; #[test] fn test_type_is_subclass() { @@ -313,14 +314,16 @@ mod tests { #[test] fn test_type_names_standard() { Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class MyClass: pass -"#, - file!(), - "test_module", +"# + ), + c_str!(file!()), + c_str!("test_module"), ) .expect("module create failed"); @@ -350,15 +353,17 @@ class MyClass: #[test] fn test_type_names_nested() { Python::with_gil(|py| { - let module = PyModule::from_code_bound( + let module = PyModule::from_code( py, - r#" + c_str!( + r#" class OuterClass: class InnerClass: pass -"#, - file!(), - "test_module", +"# + ), + c_str!(file!()), + c_str!("test_module"), ) .expect("module create failed"); diff --git a/tests/test_class_basics.rs b/tests/test_class_basics.rs index 947ab66f894..5b91ca9e695 100644 --- a/tests/test_class_basics.rs +++ b/tests/test_class_basics.rs @@ -184,7 +184,7 @@ struct EmptyClassInModule {} #[ignore] fn empty_class_in_module() { Python::with_gil(|py| { - let module = PyModule::new_bound(py, "test_module.nested").unwrap(); + let module = PyModule::new(py, "test_module.nested").unwrap(); module.add_class::().unwrap(); let ty = module.getattr("EmptyClassInModule").unwrap(); diff --git a/tests/test_class_new.rs b/tests/test_class_new.rs index f2de5df42e2..f5f980e32b9 100644 --- a/tests/test_class_new.rs +++ b/tests/test_class_new.rs @@ -169,7 +169,7 @@ c = Class() assert c.from_rust is False "# ); - let globals = PyModule::import_bound(py, "__main__").unwrap().dict(); + let globals = PyModule::import(py, "__main__").unwrap().dict(); globals.set_item("SuperClass", super_cls).unwrap(); py.run_bound(source, Some(&globals), None) .map_err(|e| e.display(py)) diff --git a/tests/test_inheritance.rs b/tests/test_inheritance.rs index 1f02edacbc8..5abdd28185c 100644 --- a/tests/test_inheritance.rs +++ b/tests/test_inheritance.rs @@ -354,7 +354,7 @@ fn module_add_class_inherit_bool_fails() { struct ExtendsBool; Python::with_gil(|py| { - let m = PyModule::new_bound(py, "test_module").unwrap(); + let m = PyModule::new(py, "test_module").unwrap(); let err = m.add_class::().unwrap_err(); assert_eq!( diff --git a/tests/test_module.rs b/tests/test_module.rs index a300ff052d3..115bbf5b6be 100644 --- a/tests/test_module.rs +++ b/tests/test_module.rs @@ -5,6 +5,7 @@ use pyo3::prelude::*; use pyo3::py_run; use pyo3::types::PyString; use pyo3::types::{IntoPyDict, PyDict, PyTuple}; +use pyo3_ffi::c_str; #[path = "../src/tests/common.rs"] mod common; @@ -158,11 +159,11 @@ fn test_module_renaming() { #[test] fn test_module_from_code_bound() { Python::with_gil(|py| { - let adder_mod = PyModule::from_code_bound( + let adder_mod = PyModule::from_code( py, - "def add(a,b):\n\treturn a+b", - "adder_mod.py", - "adder_mod", + c_str!("def add(a,b):\n\treturn a+b"), + c_str!("adder_mod.py"), + c_str!("adder_mod"), ) .expect("Module code should be loaded"); @@ -279,10 +280,10 @@ fn superfunction() -> String { #[pymodule] fn supermodule(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_function(wrap_pyfunction!(superfunction, module)?)?; - let module_to_add = PyModule::new_bound(module.py(), "submodule")?; + let module_to_add = PyModule::new(module.py(), "submodule")?; submodule(&module_to_add)?; module.add_submodule(&module_to_add)?; - let module_to_add = PyModule::new_bound(module.py(), "submodule_with_init_fn")?; + let module_to_add = PyModule::new(module.py(), "submodule_with_init_fn")?; submodule_with_init_fn(&module_to_add)?; module.add_submodule(&module_to_add)?; Ok(()) diff --git a/tests/test_proto_methods.rs b/tests/test_proto_methods.rs index 6373640a2f9..40b66c934da 100644 --- a/tests/test_proto_methods.rs +++ b/tests/test_proto_methods.rs @@ -683,7 +683,7 @@ if sys.platform == "win32" and sys.version_info >= (3, 8, 0): asyncio.run(main()) "#; - let globals = PyModule::import_bound(py, "__main__").unwrap().dict(); + let globals = PyModule::import(py, "__main__").unwrap().dict(); globals.set_item("Once", once).unwrap(); py.run_bound(source, Some(&globals), None) .map_err(|e| e.display(py)) @@ -737,7 +737,7 @@ if sys.platform == "win32" and sys.version_info >= (3, 8, 0): asyncio.run(main()) "#; - let globals = PyModule::import_bound(py, "__main__").unwrap().dict(); + let globals = PyModule::import(py, "__main__").unwrap().dict(); globals.set_item("Once", once).unwrap(); globals .set_item("AsyncIterator", py.get_type::()) @@ -809,7 +809,7 @@ del c.counter assert c.counter.count == 1 "# ); - let globals = PyModule::import_bound(py, "__main__").unwrap().dict(); + let globals = PyModule::import(py, "__main__").unwrap().dict(); globals.set_item("Counter", counter).unwrap(); py.run_bound(source, Some(&globals), None) .map_err(|e| e.display(py)) diff --git a/tests/test_various.rs b/tests/test_various.rs index b7c1ea70cfa..dc6bbc76dba 100644 --- a/tests/test_various.rs +++ b/tests/test_various.rs @@ -139,7 +139,7 @@ fn test_pickle() { } fn add_module(module: Bound<'_, PyModule>) -> PyResult<()> { - PyModule::import_bound(module.py(), "sys")? + PyModule::import(module.py(), "sys")? .dict() .get_item("modules") .unwrap() @@ -149,7 +149,7 @@ fn test_pickle() { } Python::with_gil(|py| { - let module = PyModule::new_bound(py, "test_module").unwrap(); + let module = PyModule::new(py, "test_module").unwrap(); module.add_class::().unwrap(); add_module(module).unwrap(); let inst = Py::new(py, PickleSupport {}).unwrap();