Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add PyModule::new_bound and PyModule::import_bound #3775

Merged
merged 6 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/maturin-starter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ fn maturin_starter(py: Python<'_>, m: &PyModule) -> PyResult<()> {
// Inserting to sys.modules allows importing submodules nicely from Python
// e.g. from maturin_starter.submodule import SubmoduleClass

let sys = PyModule::import(py, "sys")?;
let sys_modules: &PyDict = sys.getattr("modules")?.downcast()?;
let sys = PyModule::import_bound(py, "sys")?;
let sys_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?;
sys_modules.set_item("maturin_starter.submodule", m.getattr("submodule")?)?;

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/plugin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

// 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(py, "gadget_init_plugin")?;
let plugin = PyModule::import_bound(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()?;
Expand Down
4 changes: 2 additions & 2 deletions examples/setuptools-rust-starter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ fn _setuptools_rust_starter(py: Python<'_>, m: &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(py, "sys")?;
let sys_modules: &PyDict = sys.getattr("modules")?.downcast()?;
let sys = PyModule::import_bound(py, "sys")?;
let sys_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?;
sys_modules.set_item("setuptools_rust_starter.submodule", m.getattr("submodule")?)?;

Ok(())
Expand Down
8 changes: 4 additions & 4 deletions guide/src/class.md
Original file line number Diff line number Diff line change
Expand Up @@ -941,8 +941,8 @@ impl MyClass {
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| {
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let module = PyModule::new(py, "my_module")?;
# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?;
# let module = PyModule::new_bound(py, "my_module")?;
# module.add_class::<MyClass>()?;
# let class = module.getattr("MyClass")?;
#
Expand All @@ -951,15 +951,15 @@ impl MyClass {
# assert_eq!(doc, "");
#
# let sig: String = inspect
# .call1((class,))?
# .call1((&class,))?
# .call_method0("__str__")?
# .extract()?;
# assert_eq!(sig, "(c, d)");
# } else {
# let doc: String = class.getattr("__doc__")?.extract()?;
# assert_eq!(doc, "");
#
# inspect.call1((class,)).expect_err("`text_signature` on classes is not compatible with compilation in `abi3` mode until Python 3.10 or greater");
# inspect.call1((&class,)).expect_err("`text_signature` on classes is not compatible with compilation in `abi3` mode until Python 3.10 or greater");
# }
#
# {
Expand Down
2 changes: 1 addition & 1 deletion guide/src/class/numeric.md
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ fn my_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let globals = PyModule::import(py, "__main__")?.dict().as_borrowed();
# let globals = PyModule::import_bound(py, "__main__")?.dict();
# globals.set_item("Number", Number::type_object_bound(py))?;
#
# py.run_bound(SCRIPT, Some(&globals), None)?;
Expand Down
8 changes: 4 additions & 4 deletions guide/src/conversions/traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ struct RustyStruct {
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let module = PyModule::from_code(
# let module = PyModule::from_code_bound(
# py,
# "class Foo:
# def __init__(self):
Expand Down Expand Up @@ -111,7 +111,7 @@ struct RustyStruct {
#
# fn main() -> PyResult<()> {
# Python::with_gil(|py| -> PyResult<()> {
# let module = PyModule::from_code(
# let module = PyModule::from_code_bound(
# py,
# "class Foo(dict):
# def __init__(self):
Expand Down Expand Up @@ -339,7 +339,7 @@ enum RustyEnum<'a> {
# );
# }
# {
# let module = PyModule::from_code(
# let module = PyModule::from_code_bound(
# py,
# "class Foo(dict):
# def __init__(self):
Expand All @@ -364,7 +364,7 @@ enum RustyEnum<'a> {
# }
#
# {
# let module = PyModule::from_code(
# let module = PyModule::from_code_bound(
# py,
# "class Foo(dict):
# def __init__(self):
Expand Down
8 changes: 4 additions & 4 deletions guide/src/function/signature.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ fn increment(x: u64, amount: Option<u64>) -> u64 {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(increment, py)?;
#
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
Expand Down Expand Up @@ -166,7 +166,7 @@ fn increment(x: u64, amount: Option<u64>) -> u64 {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(increment, py)?;
#
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
Expand Down Expand Up @@ -209,7 +209,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(py, "inspect")?.getattr("signature")?;
# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
Expand Down Expand Up @@ -257,7 +257,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(py, "inspect")?.getattr("signature")?;
# let inspect = PyModule::import_bound(py, "inspect")?.getattr("signature")?;
# let sig: String = inspect
# .call1((fun,))?
# .call_method0("__str__")?
Expand Down
6 changes: 3 additions & 3 deletions guide/src/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ fn parent_module(py: Python<'_>, m: &PyModule) -> PyResult<()> {
}

fn register_child_module(py: Python<'_>, parent_module: &PyModule) -> PyResult<()> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do:

Suggested change
fn register_child_module(py: Python<'_>, parent_module: &PyModule) -> PyResult<()> {
fn register_child_module(py: Python<'_>, parent_module: &Bound<'_, PyModule>) -> PyResult<()> {

let child_module = PyModule::new(py, "child_module")?;
child_module.add_function(wrap_pyfunction!(func, child_module)?)?;
parent_module.add_submodule(child_module)?;
let child_module = PyModule::new_bound(py, "child_module")?;
child_module.add_function(&wrap_pyfunction!(func, child_module.as_gil_ref())?.as_borrowed())?;
parent_module.add_submodule(child_module.as_gil_ref())?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
parent_module.add_submodule(child_module.as_gil_ref())?;
parent_module.add_submodule(child_module)?;

Ok(())
}

Expand Down
26 changes: 13 additions & 13 deletions guide/src/python_from_rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ fn main() -> PyResult<()> {
let arg3 = "arg3";

Python::with_gil(|py| {
let fun: Py<PyAny> = PyModule::from_code(
let fun: Py<PyAny> = PyModule::from_code_bound(
py,
"def example(*args, **kwargs):
if args != ():
Expand Down Expand Up @@ -78,7 +78,7 @@ fn main() -> PyResult<()> {
let val2 = 2;

Python::with_gil(|py| {
let fun: Py<PyAny> = PyModule::from_code(
let fun: Py<PyAny> = PyModule::from_code_bound(
py,
"def example(*args, **kwargs):
if args != ():
Expand Down Expand Up @@ -134,7 +134,7 @@ use pyo3::prelude::*;

fn main() -> PyResult<()> {
Python::with_gil(|py| {
let builtins = PyModule::import(py, "builtins")?;
let builtins = PyModule::import_bound(py, "builtins")?;
let total: i32 = builtins
.getattr("sum")?
.call1((vec![1, 2, 3],))?
Expand Down Expand Up @@ -233,7 +233,7 @@ use pyo3::{

# fn main() -> PyResult<()> {
Python::with_gil(|py| {
let activators = PyModule::from_code(
let activators = PyModule::from_code_bound(
py,
r#"
def relu(x):
Expand All @@ -253,7 +253,7 @@ def leaky_relu(x, slope=0.01):
let kwargs = [("slope", 0.2)].into_py_dict_bound(py);
let lrelu_result: f64 = activators
.getattr("leaky_relu")?
.call((-1.0,), Some(kwargs.as_gil_ref()))?
.call((-1.0,), Some(&kwargs))?
.extract()?;
assert_eq!(lrelu_result, -0.2);
# Ok(())
Expand Down Expand Up @@ -310,12 +310,12 @@ pub fn add_one(x: i64) -> i64 {
fn main() -> PyResult<()> {
Python::with_gil(|py| {
// Create new module
let foo_module = PyModule::new(py, "foo")?;
foo_module.add_function(wrap_pyfunction!(add_one, foo_module)?)?;
let foo_module = PyModule::new_bound(py, "foo")?;
foo_module.add_function(&wrap_pyfunction!(add_one, foo_module.as_gil_ref())?.as_borrowed())?;

// Import and get sys.modules
let sys = PyModule::import(py, "sys")?;
let py_modules: &PyDict = sys.getattr("modules")?.downcast()?;
let sys = PyModule::import_bound(py, "sys")?;
let py_modules: Bound<'_, PyDict> = sys.getattr("modules")?.downcast_into()?;

// Insert foo into sys.modules
py_modules.set_item("foo", foo_module)?;
Expand Down Expand Up @@ -381,8 +381,8 @@ fn main() -> PyResult<()> {
));
let py_app = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python_app/app.py"));
let from_python = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
PyModule::from_code(py, py_foo, "utils.foo", "utils.foo")?;
let app: Py<PyAny> = PyModule::from_code(py, py_app, "", "")?
PyModule::from_code_bound(py, py_foo, "utils.foo", "utils.foo")?;
let app: Py<PyAny> = PyModule::from_code_bound(py, py_app, "", "")?
.getattr("run")?
.into();
app.call0(py)
Expand Down Expand Up @@ -416,7 +416,7 @@ fn main() -> PyResult<()> {
let from_python = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
let syspath = py.import_bound("sys")?.getattr("path")?.downcast_into::<PyList>()?;
syspath.insert(0, &path)?;
let app: Py<PyAny> = PyModule::from_code(py, &py_app, "", "")?
let app: Py<PyAny> = PyModule::from_code_bound(py, &py_app, "", "")?
.getattr("run")?
.into();
app.call0(py)
Expand All @@ -440,7 +440,7 @@ use pyo3::prelude::*;

fn main() {
Python::with_gil(|py| {
let custom_manager = PyModule::from_code(
let custom_manager = PyModule::from_code_bound(
py,
r#"
class House(object):
Expand Down
13 changes: 8 additions & 5 deletions pyo3-benches/benches/bench_call.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
use std::hint::black_box;

use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};

use pyo3::prelude::*;

macro_rules! test_module {
($py:ident, $code:literal) => {
PyModule::from_code($py, $code, file!(), "test_module").expect("module creation failed")
PyModule::from_code_bound($py, $code, file!(), "test_module")
.expect("module creation failed")
};
}

fn bench_call_0(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(py, "def foo(): pass");

let foo_module = module.getattr("foo").unwrap();
let foo_module = &module.getattr("foo").unwrap();

b.iter(|| {
for _ in 0..1000 {
foo_module.call0().unwrap();
black_box(foo_module).call0().unwrap();
}
});
})
Expand All @@ -33,11 +36,11 @@ class Foo:
"
);

let foo_module = module.getattr("Foo").unwrap().call0().unwrap();
let foo_module = &module.getattr("Foo").unwrap().call0().unwrap();

b.iter(|| {
for _ in 0..1000 {
foo_module.call_method0("foo").unwrap();
black_box(foo_module).call_method0("foo").unwrap();
}
});
})
Expand Down
10 changes: 6 additions & 4 deletions pyo3-benches/benches/bench_intern.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::hint::black_box;

use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};

use pyo3::prelude::*;
Expand All @@ -6,17 +8,17 @@ use pyo3::intern;

fn getattr_direct(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let sys = py.import_bound("sys").unwrap();
let sys = &py.import_bound("sys").unwrap();

b.iter(|| sys.getattr("version").unwrap());
b.iter(|| black_box(sys).getattr("version").unwrap());
});
}

fn getattr_intern(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let sys = py.import_bound("sys").unwrap();
let sys = &py.import_bound("sys").unwrap();

b.iter(|| sys.getattr(intern!(py, "version")).unwrap());
b.iter(|| black_box(sys).getattr(intern!(py, "version")).unwrap());
});
}

Expand Down
4 changes: 2 additions & 2 deletions pytests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ fn pyo3_pytests(py: Python<'_>, m: &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(py, "sys")?;
let sys_modules: &PyDict = sys.getattr("modules")?.downcast()?;
let sys = PyModule::import_bound(py, "sys")?;
let sys_modules = sys.getattr("modules")?.downcast_into::<PyDict>()?;
sys_modules.set_item("pyo3_pytests.awaitable", m.getattr("awaitable")?)?;
sys_modules.set_item("pyo3_pytests.buf_and_str", m.getattr("buf_and_str")?)?;
sys_modules.set_item("pyo3_pytests.comparisons", m.getattr("comparisons")?)?;
Expand Down
2 changes: 1 addition & 1 deletion src/conversions/anyhow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
//! // could call inside an application...
//! // This might return a `PyErr`.
//! let res = Python::with_gil(|py| {
//! let zlib = PyModule::import(py, "zlib")?;
//! let zlib = PyModule::import_bound(py, "zlib")?;
//! let decompress = zlib.getattr("decompress")?;
//! let bytes = PyBytes::new_bound(py, bytes);
//! let value = decompress.call1((bytes,))?;
Expand Down
2 changes: 1 addition & 1 deletion src/conversions/chrono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ fn timezone_utc_bound(py: Python<'_>) -> Bound<'_, PyAny> {
#[cfg(test)]
mod tests {
use super::*;
use crate::{types::PyTuple, Py};
use crate::{types::PyTuple, Bound, Py};
use std::{cmp::Ordering, panic};

#[test]
Expand Down
2 changes: 2 additions & 0 deletions src/conversions/chrono_tz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ impl FromPyObject<'_> for Tz {

#[cfg(all(test, not(windows)))] // Troubles loading timezones on Windows
mod tests {
use crate::{types::any::PyAnyMethods, Bound};

use super::*;

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/conversions/eyre.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
//! // could call inside an application...
//! // This might return a `PyErr`.
//! let res = Python::with_gil(|py| {
//! let zlib = PyModule::import(py, "zlib")?;
//! let zlib = PyModule::import_bound(py, "zlib")?;
//! let decompress = zlib.getattr("decompress")?;
//! let bytes = PyBytes::new_bound(py, bytes);
//! let value = decompress.call1((bytes,))?;
Expand Down
9 changes: 6 additions & 3 deletions src/conversions/num_bigint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,10 @@ fn int_n_bits(long: &Bound<'_, PyLong>) -> PyResult<usize> {
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{PyDict, PyModule};
use crate::{
types::{PyDict, PyModule},
Bound,
};
use indoc::indoc;

fn rust_fib<T>() -> impl Iterator<Item = T>
Expand Down Expand Up @@ -323,7 +326,7 @@ mod tests {
});
}

fn python_index_class(py: Python<'_>) -> &PyModule {
fn python_index_class(py: Python<'_>) -> Bound<'_, PyModule> {
let index_code = indoc!(
r#"
class C:
Expand All @@ -333,7 +336,7 @@ mod tests {
return self.x
"#
);
PyModule::from_code(py, index_code, "index.py", "index").unwrap()
PyModule::from_code_bound(py, index_code, "index.py", "index").unwrap()
}

#[test]
Expand Down
Loading
Loading