Struct pyo3::types::PyModule

source ·
#[repr(transparent)]
pub struct PyModule(_);
Expand description

Represents a Python module object.

As with all other Python objects, modules are first class citizens. This means they can be passed to or returned from functions, created dynamically, assigned to variables and so forth.

Implementations§

Creates a new module object with the __name__ attribute set to name.

Examples
use pyo3::prelude::*;

Python::with_gil(|py| -> PyResult<()> {
    let module = PyModule::new(py, "my_module")?;

    assert_eq!(module.name()?, "my_module");
    Ok(())
})?;

Imports the Python module with the specified name.

Examples
use pyo3::prelude::*;

Python::with_gil(|py| {
    let module = PyModule::import(py, "antigravity").expect("No flying for you.");
});

This is equivalent to the following Python expression:

import antigravity

Creates and loads a module named module_name, containing the Python code passed to code and pretending to live at file_name.

⚠ ️
 Warning: This will compile and execute code. Never pass untrusted code to this function!

Errors

Returns PyErr if:

  • code is not syntactically correct Python.
  • Any Python exceptions are raised while initializing the module.
  • Any of the arguments cannot be converted to CStrings.
Example: bundle in a file at compile time with include_str!:
use pyo3::prelude::*;

// This path is resolved relative to this file.
let code = include_str!("../../assets/script.py");

Python::with_gil(|py| -> PyResult<()> {
    PyModule::from_code(py, code, "example", "example")?;
    Ok(())
})?;
Example: Load a file at runtime with std::fs::read_to_string.
use pyo3::prelude::*;

// This path is resolved by however the platform resolves paths,
// which also makes this less portable. Consider using `include_str`
// if you just want to bundle a script with your module.
let code = std::fs::read_to_string("assets/script.py")?;

Python::with_gil(|py| -> PyResult<()> {
    PyModule::from_code(py, &code, "example", "example")?;
    Ok(())
})?;
Ok(())

Returns the module’s __dict__ attribute, which contains the module’s symbol table.

Returns the index (the __all__ attribute) of the module, creating one if needed.

__all__ declares the items that will be imported with from my_module import *.

Returns the name (the __name__ attribute) of the module.

May fail if the module does not have a __name__ attribute.

Available on non-PyPy only.

Returns the filename (the __file__ attribute) of the module.

May fail if the module does not have a __file__ attribute.

Adds an attribute to the module.

For adding classes, functions or modules, prefer to use PyModule::add_class, PyModule::add_function or PyModule::add_submodule instead, respectively.

Examples
use pyo3::prelude::*;

#[pymodule]
fn my_module(_py: Python<'_>, module: &PyModule) -> PyResult<()> {
    module.add("c", 299_792_458)?;
    Ok(())
}

Python code can then do the following:

from my_module import c

print("c is", c)

This will result in the following output:

c is 299792458

Adds a new class to the module.

Notice that this method does not take an argument. Instead, this method is generic, and requires us to use the “turbofish” syntax to specify the class we want to add.

Examples
use pyo3::prelude::*;

#[pyclass]
struct Foo { /* fields omitted */ }

#[pymodule]
fn my_module(_py: Python<'_>, module: &PyModule) -> PyResult<()> {
    module.add_class::<Foo>()?;
    Ok(())
}

Python code can see this class as such:

from my_module import Foo

print("Foo is", Foo)

This will result in the following output:

Foo is <class 'builtins.Foo'>

Note that as we haven’t defined a constructor, Python code can’t actually make an instance of Foo (or get one for that matter, as we haven’t exported anything that can return instances of Foo).

Adds a function or a (sub)module to a module, using the functions name as name.

Prefer to use PyModule::add_function and/or PyModule::add_submodule instead.

Adds a submodule to a module.

This is especially useful for creating module hierarchies.

Note that this doesn’t define a package, so this won’t allow Python code to directly import submodules by using from my_module import submodule. For more information, see #759 and #1517.

Examples
use pyo3::prelude::*;

#[pymodule]
fn my_module(py: Python<'_>, module: &PyModule) -> PyResult<()> {
    let submodule = PyModule::new(py, "submodule")?;
    submodule.add("super_useful_constant", "important")?;

    module.add_submodule(submodule)?;
    Ok(())
}

Python code can then do the following:

import my_module

print("super_useful_constant is", my_module.submodule.super_useful_constant)

This will result in the following output:

super_useful_constant is important

Add a function to a module.

Note that this also requires the wrap_pyfunction! macro to wrap a function annotated with #[pyfunction].

use pyo3::prelude::*;

#[pyfunction]
fn say_hello() {
    println!("Hello world!")
}
#[pymodule]
fn my_module(_py: Python<'_>, module: &PyModule) -> PyResult<()> {
    module.add_function(wrap_pyfunction!(say_hello, module)?)
}

Python code can then do the following:

from my_module import say_hello

say_hello()

This will result in the following output:

Hello world!

Methods from Deref<Target = PyAny>§

Returns whether self and other point to the same object. To compare the equality of two objects (the == operator), use eq.

This is equivalent to the Python expression self is other.

Determines whether this object has the given attribute.

This is equivalent to the Python expression hasattr(self, attr_name).

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern attr_name.

Retrieves an attribute value.

This is equivalent to the Python expression self.attr_name.

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern attr_name.

Example: intern!ing the attribute name
#[pyfunction]
fn version(sys: &PyModule) -> PyResult<&PyAny> {
    sys.getattr(intern!(sys.py(), "version"))
}

Sets an attribute value.

This is equivalent to the Python expression self.attr_name = value.

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Example: intern!ing the attribute name
#[pyfunction]
fn set_answer(ob: &PyAny) -> PyResult<()> {
    ob.setattr(intern!(ob.py(), "answer"), 42)
}

Deletes an attribute.

This is equivalent to the Python statement del self.attr_name.

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern attr_name.

Returns an Ordering between self and other.

This is equivalent to the following Python code:

if self == other:
    return Equal
elif a < b:
    return Less
elif a > b:
    return Greater
else:
    raise TypeError("PyAny::compare(): All comparisons returned false")
Examples
use pyo3::prelude::*;
use pyo3::types::PyFloat;
use std::cmp::Ordering;

Python::with_gil(|py| -> PyResult<()> {
    let a = PyFloat::new(py, 0_f64);
    let b = PyFloat::new(py, 42_f64);
    assert_eq!(a.compare(b)?, Ordering::Less);
    Ok(())
})?;

It will return PyErr for values that cannot be compared:

use pyo3::prelude::*;
use pyo3::types::{PyFloat, PyString};

Python::with_gil(|py| -> PyResult<()> {
    let a = PyFloat::new(py, 0_f64);
    let b = PyString::new(py, "zero");
    assert!(a.compare(b).is_err());
    Ok(())
})?;

Tests whether two Python objects obey a given CompareOp.

lt, le, eq, ne, gt and ge are the specialized versions of this function.

Depending on the value of compare_op, this is equivalent to one of the following Python expressions:

compare_opPython expression
CompareOp::Eqself == other
CompareOp::Neself != other
CompareOp::Ltself < other
CompareOp::Leself <= other
CompareOp::Gtself > other
CompareOp::Geself >= other
Examples
use pyo3::class::basic::CompareOp;
use pyo3::prelude::*;
use pyo3::types::PyInt;

Python::with_gil(|py| -> PyResult<()> {
    let a: &PyInt = 0_u8.into_py(py).into_ref(py).downcast()?;
    let b: &PyInt = 42_u8.into_py(py).into_ref(py).downcast()?;
    assert!(a.rich_compare(b, CompareOp::Le)?.is_true()?);
    Ok(())
})?;

Tests whether this object is less than another.

This is equivalent to the Python expression self < other.

Tests whether this object is less than or equal to another.

This is equivalent to the Python expression self <= other.

Tests whether this object is equal to another.

This is equivalent to the Python expression self == other.

Tests whether this object is not equal to another.

This is equivalent to the Python expression self != other.

Tests whether this object is greater than another.

This is equivalent to the Python expression self > other.

Tests whether this object is greater than or equal to another.

This is equivalent to the Python expression self >= other.

Determines whether this object appears callable.

This is equivalent to Python’s callable() function.

Examples
use pyo3::prelude::*;

Python::with_gil(|py| -> PyResult<()> {
    let builtins = PyModule::import(py, "builtins")?;
    let print = builtins.getattr("print")?;
    assert!(print.is_callable());
    Ok(())
})?;

This is equivalent to the Python statement assert callable(print).

Note that unless an API needs to distinguish between callable and non-callable objects, there is no point in checking for callability. Instead, it is better to just do the call and handle potential exceptions.

Calls the object.

This is equivalent to the Python expression self(*args, **kwargs).

Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;

const CODE: &str = r#"
def function(*args, **kwargs):
    assert args == ("hello",)
    assert kwargs == {"cruel": "world"}
    return "called with args and kwargs"
"#;

Python::with_gil(|py| {
    let module = PyModule::from_code(py, CODE, "", "")?;
    let fun = module.getattr("function")?;
    let args = ("hello",);
    let kwargs = PyDict::new(py);
    kwargs.set_item("cruel", "world")?;
    let result = fun.call(args, Some(kwargs))?;
    assert_eq!(result.extract::<&str>()?, "called with args and kwargs");
    Ok(())
})

Calls the object without arguments.

This is equivalent to the Python expression self().

Examples
use pyo3::prelude::*;

Python::with_gil(|py| -> PyResult<()> {
    let module = PyModule::import(py, "builtins")?;
    let help = module.getattr("help")?;
    help.call0()?;
    Ok(())
})?;

This is equivalent to the Python expression help().

Calls the object with only positional arguments.

This is equivalent to the Python expression self(*args).

Examples
use pyo3::prelude::*;

const CODE: &str = r#"
def function(*args, **kwargs):
    assert args == ("hello",)
    assert kwargs == {}
    return "called with args"
"#;

Python::with_gil(|py| {
    let module = PyModule::from_code(py, CODE, "", "")?;
    let fun = module.getattr("function")?;
    let args = ("hello",);
    let result = fun.call1(args)?;
    assert_eq!(result.extract::<&str>()?, "called with args");
    Ok(())
})

Calls a method on the object.

This is equivalent to the Python expression self.name(*args, **kwargs).

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;

const CODE: &str = r#"
class A:
    def method(self, *args, **kwargs):
        assert args == ("hello",)
        assert kwargs == {"cruel": "world"}
        return "called with args and kwargs"
a = A()
"#;

Python::with_gil(|py| {
    let module = PyModule::from_code(py, CODE, "", "")?;
    let instance = module.getattr("a")?;
    let args = ("hello",);
    let kwargs = PyDict::new(py);
    kwargs.set_item("cruel", "world")?;
    let result = instance.call_method("method", args, Some(kwargs))?;
    assert_eq!(result.extract::<&str>()?, "called with args and kwargs");
    Ok(())
})

Calls a method on the object without arguments.

This is equivalent to the Python expression self.name().

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Examples
use pyo3::prelude::*;

const CODE: &str = r#"
class A:
    def method(self, *args, **kwargs):
        assert args == ()
        assert kwargs == {}
        return "called with no arguments"
a = A()
"#;

Python::with_gil(|py| {
    let module = PyModule::from_code(py, CODE, "", "")?;
    let instance = module.getattr("a")?;
    let result = instance.call_method0("method")?;
    assert_eq!(result.extract::<&str>()?, "called with no arguments");
    Ok(())
})

Calls a method on the object with only positional arguments.

This is equivalent to the Python expression self.name(*args).

To avoid repeated temporary allocations of Python strings, the intern! macro can be used to intern name.

Examples
use pyo3::prelude::*;

const CODE: &str = r#"
class A:
    def method(self, *args, **kwargs):
        assert args == ("hello",)
        assert kwargs == {}
        return "called with args"
a = A()
"#;

Python::with_gil(|py| {
    let module = PyModule::from_code(py, CODE, "", "")?;
    let instance = module.getattr("a")?;
    let args = ("hello",);
    let result = instance.call_method1("method", args)?;
    assert_eq!(result.extract::<&str>()?, "called with args");
    Ok(())
})

Returns whether the object is considered to be true.

This is equivalent to the Python expression bool(self).

Returns whether the object is considered to be None.

This is equivalent to the Python expression self is None.

Returns true if the sequence or mapping has a length of 0.

This is equivalent to the Python expression len(self) == 0.

Gets an item from the collection.

This is equivalent to the Python expression self[key].

Sets a collection item value.

This is equivalent to the Python expression self[key] = value.

Deletes an item from the collection.

This is equivalent to the Python expression del self[key].

Takes an object and returns an iterator for it.

This is typically a new iterator but if the argument is an iterator, this returns itself.

Returns the Python type object for this object’s type.

Returns the Python type pointer for this object.

👎Deprecated since 0.18.0: use the equivalent .downcast()

Converts this PyAny to a concrete Python type.

Converts this PyAny to a concrete Python type.

This can cast only to native Python types, not types implemented in Rust.

Examples
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyDict, PyList};

Python::with_gil(|py| {
    let dict = PyDict::new(py);
    assert!(dict.is_instance_of::<PyAny>().unwrap());
    let any: &PyAny = dict.as_ref();
    assert!(any.downcast::<PyDict>().is_ok());
    assert!(any.downcast::<PyList>().is_err());
});

Converts this PyAny to a concrete Python type without checking validity.

Safety

Callers must ensure that the type is valid or risk type confusion.

Extracts some type from the Python object.

This is a wrapper function around FromPyObject::extract().

Returns the reference count for the Python object.

Computes the “repr” representation of self.

This is equivalent to the Python expression repr(self).

Computes the “str” representation of self.

This is equivalent to the Python expression str(self).

Retrieves the hash code of self.

This is equivalent to the Python expression hash(self).

Returns the length of the sequence or mapping.

This is equivalent to the Python expression len(self).

Returns the list of attributes of this object.

This is equivalent to the Python expression dir(self).

Checks whether this object is an instance of type ty.

This is equivalent to the Python expression isinstance(self, ty).

Checks whether this object is an instance of type T.

This is equivalent to the Python expression isinstance(self, T), if the type T is known at compile time.

Determines if self contains value.

This is equivalent to the Python expression value in self.

Returns a GIL marker constrained to the lifetime of this type.

Available on non-PyPy only.

Return a proxy object that delegates method calls to a parent or sibling class of type.

This is equivalent to the Python expression super()

Trait Implementations§

Gets the underlying FFI pointer, returns a borrowed pointer.

Converts this type into a shared reference of the (usually inferred) input type.
Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Extracts Self from the source PyObject.
Performs the conversion.
Returns a GIL marker constrained to the lifetime of this type.
Cast &PyAny to &Self without no type checking. Read more
Utility type to make Py::as_ref work.
Class name.
Module name, if any.
Returns the PyTypeObject instance for this type.
Checks if object is an instance of this type or a subclass of this type.
Returns the safe abstraction over the type object.
Checks if object is an instance of this type.
Converts self into a Python object.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Convert from an arbitrary PyObject. Read more
Convert from an arbitrary borrowed PyObject. Read more
Convert from an arbitrary PyObject or panic. Read more
Convert from an arbitrary PyObject or panic. Read more
Convert from an arbitrary PyObject. Read more
Convert from an arbitrary borrowed PyObject. Read more
Convert from an arbitrary borrowed PyObject. Read more
Convert from an arbitrary borrowed PyObject. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Cast from a concrete Python object type to PyObject.
Cast from a concrete Python object type to PyObject. With exact type check.
Cast a PyAny to a specific type of PyObject. The caller must have already verified the reference is for this type. Read more
👎Deprecated since 0.17.0: this trait is no longer used by PyO3, use ToPyObject or IntoPy<PyObject>
Converts self into a Python object and calls the specified closure on the native FFI pointer underlying the Python object. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.