Skip to main content

PyModule

Struct PyModule 

pub struct PyModule(/* private fields */);
Available on crate feature tls only.
Expand description

Represents a Python module object.

Values of this type are accessed via PyO3’s smart pointers, e.g. as Py<PyModule> or Bound<'py, PyModule>.

For APIs available on module objects, see the PyModuleMethods trait which is implemented for Bound<'py, PyModule>.

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§

§

impl PyModule

pub fn new<'py>( py: Python<'py>, name: &str, ) -> Result<Bound<'py, PyModule>, PyErr>

Creates a new module object with the __name__ attribute set to name. When creating a submodule pass the full path as the name such as top_level.name.

§Examples
use pyo3::prelude::*;

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

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

pub fn import<'py, N>( py: Python<'py>, name: N, ) -> Result<Bound<'py, PyModule>, PyErr>
where N: IntoPyObject<'py, Target = PyString>,

Imports the Python module with the specified name.

§Examples
use pyo3::prelude::*;

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

This is equivalent to the following Python expression:

import antigravity

If you want to import a class, you can store a reference to it with PyOnceLock::import.

pub fn from_code<'py>( py: Python<'py>, code: &CStr, file_name: &CStr, module_name: &CStr, ) -> Result<Bound<'py, PyModule>, PyErr>

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

If file_name is empty, it will be set to <string>.

⚠ ️
 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::*;
use pyo3::ffi::c_str;

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

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

// 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::attach(|py| -> PyResult<()> {
    PyModule::from_code(py, CString::new(code)?.as_c_str(), c"example.py", c"example")?;
    Ok(())
})?;

Trait Implementations§

§

impl PyTypeInfo for PyModule

§

const NAME: &'static str = "PyModule"

👎Deprecated since 0.28.0:

prefer using ::type_object(py).name() to get the correct runtime value

Class name.
§

const MODULE: Option<&'static str>

👎Deprecated since 0.28.0:

prefer using ::type_object(py).module() to get the correct runtime value

Module name, if any.
§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
§

fn is_type_of(obj: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
§

impl DerefToPyAny for PyModule

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

const NAME: &'static str = T::NAME

👎Deprecated since 0.27.0:

Use ::classinfo_object() instead and format the type name at runtime. Note that using built-in cast features is often better than manual PyTypeCheck usage.

Name of self. This is used in error messages, for example.
§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
§

fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

Returns the expected type as a possible argument for the isinstance and issubclass function. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more