Skip to content

Commit

Permalink
add PyModule::new and PyModule::import_bound
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Feb 14, 2024
1 parent 0c12d91 commit 3eb45fb
Show file tree
Hide file tree
Showing 23 changed files with 144 additions and 102 deletions.
2 changes: 1 addition & 1 deletion guide/src/class.md
Original file line number Diff line number Diff line change
Expand Up @@ -941,7 +941,7 @@ 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 module = PyModule::new_bound(py, "my_module")?;
# module.add_class::<MyClass>()?;
# let class = module.getattr("MyClass")?;
#
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<()> {
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())?)?;
parent_module.add_submodule(child_module.as_gil_ref())?;
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion guide/src/python_from_rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ pub fn add_one(x: i64) -> i64 {
fn main() -> PyResult<()> {
Python::with_gil(|py| {
// Create new module
let foo_module = PyModule::new(py, "foo")?;
let foo_module = PyModule::new_bound(py, "foo")?;
foo_module.add_function(wrap_pyfunction!(add_one, foo_module)?)?;

// Import and get sys.modules
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("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("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
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
9 changes: 6 additions & 3 deletions src/conversions/num_bigint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,10 @@ mod tests {
use self::{any::PyAnyMethods, dict::PyDictMethods};

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 @@ -329,7 +332,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 @@ -339,7 +342,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
12 changes: 6 additions & 6 deletions src/conversions/num_complex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
//! #
//! # fn main() -> PyResult<()> {
//! # Python::with_gil(|py| -> PyResult<()> {
//! # let module = PyModule::new(py, "my_module")?;
//! # let module = PyModule::new_bound(py, "my_module")?;
//! #
//! # module.add_function(wrap_pyfunction!(get_eigenvalues, module)?)?;
//! #
Expand Down Expand Up @@ -183,7 +183,7 @@ complex_conversion!(f64);
#[cfg(test)]
mod tests {
use super::*;
use crate::types::PyModule;
use crate::types::{any::PyAnyMethods, PyModule};

#[test]
fn from_complex() {
Expand Down Expand Up @@ -212,7 +212,7 @@ mod tests {
#[test]
fn from_python_magic() {
Python::with_gil(|py| {
let module = PyModule::from_code(
let module = PyModule::from_code_bound(
py,
r#"
class A:
Expand Down Expand Up @@ -250,7 +250,7 @@ class C:
#[test]
fn from_python_inherited_magic() {
Python::with_gil(|py| {
let module = PyModule::from_code(
let module = PyModule::from_code_bound(
py,
r#"
class First: pass
Expand Down Expand Up @@ -294,7 +294,7 @@ 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(
let module = PyModule::from_code_bound(
py,
r#"
class A:
Expand All @@ -317,7 +317,7 @@ 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(
let module = PyModule::from_code_bound(
py,
r#"
class MyComplex:
Expand Down
6 changes: 3 additions & 3 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ impl<T> IntoPy<PyObject> for Borrowed<'_, '_, T> {
/// #
/// # fn main() -> PyResult<()> {
/// # Python::with_gil(|py| {
/// # let m = pyo3::types::PyModule::new(py, "test")?;
/// # let m = pyo3::types::PyModule::new_bound(py, "test")?;
/// # m.add_class::<Foo>()?;
/// #
/// # let foo: &PyCell<Foo> = m.getattr("Foo")?.call0()?.downcast()?;
Expand Down Expand Up @@ -679,7 +679,7 @@ impl<T> IntoPy<PyObject> for Borrowed<'_, '_, T> {
/// #
/// # fn main() -> PyResult<()> {
/// # Python::with_gil(|py| {
/// # let m = pyo3::types::PyModule::new(py, "test")?;
/// # let m = pyo3::types::PyModule::new_bound(py, "test")?;
/// # m.add_class::<Foo>()?;
/// #
/// # let foo: &PyCell<Foo> = m.getattr("Foo")?.call0()?.downcast()?;
Expand Down Expand Up @@ -1233,7 +1233,7 @@ impl<T> Py<T> {
/// }
/// #
/// # Python::with_gil(|py| {
/// # let ob = PyModule::new(py, "empty").unwrap().into_py(py);
/// # let ob = PyModule::new_bound(py, "empty").unwrap().into_py(py);
/// # set_answer(ob, py).unwrap();
/// # });
/// ```
Expand Down
7 changes: 2 additions & 5 deletions src/marker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@ impl<'py> Python<'py> {
where
N: IntoPy<Py<PyString>>,
{
#[allow(deprecated)]
PyModule::import(self, name)
}

Expand All @@ -756,11 +757,7 @@ impl<'py> Python<'py> {
where
N: IntoPy<Py<PyString>>,
{
// FIXME: This should be replaced by `PyModule::import_bound` once thats
// implemented.
PyModule::import(self, name)
.map(PyNativeType::as_borrowed)
.map(crate::Borrowed::to_owned)
PyModule::import_bound(self, name)
}

/// Gets the Python builtin value `None`.
Expand Down
2 changes: 1 addition & 1 deletion src/pyclass_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ impl<T: PyClass> PyClassInitializer<T> {
///
/// fn main() -> PyResult<()> {
/// Python::with_gil(|py| {
/// let m = PyModule::new(py, "example")?;
/// let m = PyModule::new_bound(py, "example")?;
/// m.add_class::<SubClass>()?;
/// m.add_class::<BaseClass>()?;
///
Expand Down
12 changes: 6 additions & 6 deletions src/types/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,13 @@ impl PyAny {
/// # use pyo3::{intern, pyfunction, types::PyModule, PyAny, Python, PyResult};
/// #
/// #[pyfunction]
/// fn set_answer(ob: &PyAny) -> PyResult<()> {
/// fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> {
/// ob.setattr(intern!(ob.py(), "answer"), 42)
/// }
/// #
/// # Python::with_gil(|py| {
/// # let ob = PyModule::new(py, "empty").unwrap();
/// # set_answer(ob).unwrap();
/// # let ob = PyModule::new_bound(py, "empty").unwrap();
/// # set_answer(&ob).unwrap();
/// # });
/// ```
pub fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
Expand Down Expand Up @@ -1011,13 +1011,13 @@ pub trait PyAnyMethods<'py> {
/// # use pyo3::{intern, pyfunction, types::PyModule, PyAny, Python, PyResult};
/// #
/// #[pyfunction]
/// fn set_answer(ob: &PyAny) -> PyResult<()> {
/// fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> {
/// ob.setattr(intern!(ob.py(), "answer"), 42)
/// }
/// #
/// # Python::with_gil(|py| {
/// # let ob = PyModule::new(py, "empty").unwrap();
/// # set_answer(ob).unwrap();
/// # let ob = PyModule::new_bound(py, "empty").unwrap();
/// # set_answer(&ob).unwrap();
/// # });
/// ```
fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
Expand Down
1 change: 1 addition & 0 deletions src/types/capsule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ fn name_ptr_ignore_error(slf: &Bound<'_, PyCapsule>) -> *const c_char {
}

#[cfg(test)]
#[cfg_attr(not(feature = "gil-refs"), allow(deprecated))]
mod tests {
use libc::c_void;

Expand Down
Loading

0 comments on commit 3eb45fb

Please sign in to comment.