Skip to main content

pyo3/types/
module.rs

1use crate::err::{PyErr, PyResult};
2use crate::ffi_ptr_ext::FfiPtrExt;
3use crate::impl_::callback::IntoPyCallbackOutput;
4use crate::py_result_ext::PyResultExt;
5use crate::pyclass::PyClass;
6use crate::types::{
7    PyAny, PyCFunction, PyDict, PyList, PyString, any::PyAnyMethods, list::PyListMethods,
8    string::PyStringMethods,
9};
10use crate::{
11    Borrowed, Bound, BoundObject, IntoPyObject, IntoPyObjectExt, Py, Python, exceptions, ffi,
12};
13#[cfg(RustPython)]
14use crate::{
15    sync::PyOnceLock,
16    types::{PyType, PyTypeMethods},
17};
18use alloc::borrow::Cow;
19use core::ffi::CStr;
20#[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))]
21use core::ffi::c_int;
22use core::str;
23
24/// Represents a Python [`module`][1] object.
25///
26/// Values of this type are accessed via PyO3's smart pointers, e.g. as
27/// [`Py<PyModule>`][crate::Py] or [`Bound<'py, PyModule>`][Bound].
28///
29/// For APIs available on `module` objects, see the [`PyModuleMethods`] trait which is implemented for
30/// [`Bound<'py, PyModule>`][Bound].
31///
32/// As with all other Python objects, modules are first class citizens.
33/// This means they can be passed to or returned from functions,
34/// created dynamically, assigned to variables and so forth.
35///
36/// [1]: https://docs.python.org/3/tutorial/modules.html
37#[repr(transparent)]
38pub struct PyModule(PyAny);
39
40#[cfg(not(RustPython))]
41pyobject_native_type_core!(PyModule, pyobject_native_static_type_object!(ffi::PyModule_Type), "types", "ModuleType", #checkfunction=ffi::PyModule_Check);
42
43#[cfg(RustPython)]
44pyobject_native_type_core!(
45    PyModule,
46    |py| {
47        static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
48        TYPE.import(py, "types", "ModuleType").unwrap().as_type_ptr()
49    },
50    "types",
51    "ModuleType",
52    #checkfunction=ffi::PyModule_Check
53);
54
55impl PyModule {
56    /// Creates a new module object with the `__name__` attribute set to `name`.  When creating
57    /// a submodule pass the full path as the name such as `top_level.name`.
58    ///
59    /// # Examples
60    ///
61    /// ``` rust
62    /// use pyo3::prelude::*;
63    ///
64    /// # fn main() -> PyResult<()> {
65    /// Python::attach(|py| -> PyResult<()> {
66    ///     let module = PyModule::new(py, "my_module")?;
67    ///
68    ///     assert_eq!(module.name()?, "my_module");
69    ///     Ok(())
70    /// })?;
71    /// # Ok(())}
72    ///  ```
73    pub fn new<'py>(py: Python<'py>, name: &str) -> PyResult<Bound<'py, PyModule>> {
74        let name = PyString::new(py, name);
75        let module = unsafe {
76            ffi::PyModule_NewObject(name.as_ptr())
77                .assume_owned_or_err(py)?
78                .cast_into_unchecked()
79        };
80
81        // By default, PyO3 assumes modules do not use the GIL for thread safety.
82        module.gil_used(false)?;
83
84        Ok(module)
85    }
86
87    /// Imports the Python module with the specified name.
88    ///
89    /// # Examples
90    ///
91    /// ```no_run
92    /// # fn main() {
93    /// use pyo3::prelude::*;
94    ///
95    /// Python::attach(|py| {
96    ///     let module = PyModule::import(py, "antigravity").expect("No flying for you.");
97    /// });
98    /// # }
99    ///  ```
100    ///
101    /// This is equivalent to the following Python expression:
102    /// ```python
103    /// import antigravity
104    /// ```
105    ///
106    /// If you want to import a class, you can store a reference to it with
107    /// [`PyOnceLock::import`][crate::sync::PyOnceLock::import].
108    pub fn import<'py, N>(py: Python<'py>, name: N) -> PyResult<Bound<'py, PyModule>>
109    where
110        N: IntoPyObject<'py, Target = PyString>,
111    {
112        let name = name.into_pyobject_or_pyerr(py)?;
113        unsafe {
114            ffi::PyImport_Import(name.as_ptr())
115                .assume_owned_or_err(py)
116                .cast_into_unchecked()
117        }
118    }
119
120    /// Creates and loads a module named `module_name`,
121    /// containing the Python code passed to `code`
122    /// and pretending to live at `file_name`.
123    ///
124    /// If `file_name` is empty, it will be set to `<string>`.
125    ///
126    /// <div class="information">
127    ///     <div class="tooltip compile_fail" style="">&#x26a0; &#xfe0f;</div>
128    /// </div><div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
129    /// <strong>Warning</strong>: This will compile and execute code. <strong>Never</strong> pass untrusted code to this function!
130    /// </pre></div>
131    ///
132    /// # Errors
133    ///
134    /// Returns `PyErr` if:
135    /// - `code` is not syntactically correct Python.
136    /// - Any Python exceptions are raised while initializing the module.
137    /// - Any of the arguments cannot be converted to [`CString`][alloc::ffi::CString]s.
138    ///
139    /// # Example: bundle in a file at compile time with [`include_str!`][core::include_str]:
140    ///
141    /// <!-- Using standalone_crate ensures that the `include_str!` is resolved relative to this
142    /// file, not the workspace root, when merged doctests are being compiled. -->
143    ///
144    /// ```rust,standalone_crate
145    /// use pyo3::prelude::*;
146    /// use pyo3::ffi::c_str;
147    ///
148    /// # fn main() -> PyResult<()> {
149    /// // This path is resolved relative to this file.
150    /// let code = c_str!(include_str!("../../assets/script.py"));
151    ///
152    /// Python::attach(|py| -> PyResult<()> {
153    ///     PyModule::from_code(py, code, c"example.py", c"example")?;
154    ///     Ok(())
155    /// })?;
156    /// # Ok(())
157    /// # }
158    /// ```
159    ///
160    /// # Example: Load a file at runtime with [`std::fs::read_to_string`].
161    ///
162    /// ```rust
163    /// use pyo3::prelude::*;
164    /// use std::ffi::CString;
165    ///
166    /// # #[cfg(not(wip_feature_std))]
167    /// fn main() {}
168    ///
169    /// # #[cfg(wip_feature_std)]
170    /// # fn main() -> PyResult<()> {
171    /// # #[cfg(not(target_arch = "wasm32"))]  // node fs doesn't see this file, maybe cwd wrong?
172    /// # {
173    /// // This path is resolved by however the platform resolves paths,
174    /// // which also makes this less portable. Consider using `include_str`
175    /// // if you just want to bundle a script with your module.
176    /// let code = std::fs::read_to_string("assets/script.py")?;
177    ///
178    /// Python::attach(|py| -> PyResult<()> {
179    ///     PyModule::from_code(py, CString::new(code)?.as_c_str(), c"example.py", c"example")?;
180    ///     Ok(())
181    /// })?;
182    /// # }
183    /// # Ok(())
184    /// # }
185    /// ```
186    pub fn from_code<'py>(
187        py: Python<'py>,
188        code: &CStr,
189        file_name: &CStr,
190        module_name: &CStr,
191    ) -> PyResult<Bound<'py, PyModule>> {
192        let file_name = if file_name.is_empty() {
193            c"<string>"
194        } else {
195            file_name
196        };
197        unsafe {
198            let code = ffi::Py_CompileString(code.as_ptr(), file_name.as_ptr(), ffi::Py_file_input)
199                .assume_owned_or_err(py)?;
200
201            ffi::PyImport_ExecCodeModuleEx(module_name.as_ptr(), code.as_ptr(), file_name.as_ptr())
202                .assume_owned_or_err(py)
203                .cast_into()
204        }
205    }
206}
207
208/// Implementation of functionality for [`PyModule`].
209///
210/// These methods are defined for the `Bound<'py, PyModule>` smart pointer, so to use method call
211/// syntax these methods are separated into a trait, because stable Rust does not yet support
212/// `arbitrary_self_types`.
213#[doc(alias = "PyModule")]
214pub trait PyModuleMethods<'py>: crate::sealed::Sealed {
215    /// Returns the module's `__dict__` attribute, which contains the module's symbol table.
216    fn dict(&self) -> Bound<'py, PyDict>;
217
218    /// Returns the index (the `__all__` attribute) of the module,
219    /// creating one if needed.
220    ///
221    /// `__all__` declares the items that will be imported with `from my_module import *`.
222    fn index(&self) -> PyResult<Bound<'py, PyList>>;
223
224    /// Returns the name (the `__name__` attribute) of the module.
225    ///
226    /// May fail if the module does not have a `__name__` attribute.
227    fn name(&self) -> PyResult<Bound<'py, PyString>>;
228
229    /// Returns the filename (the `__file__` attribute) of the module.
230    ///
231    /// May fail if the module does not have a `__file__` attribute.
232    fn filename(&self) -> PyResult<Bound<'py, PyString>>;
233
234    /// Adds an attribute to the module.
235    ///
236    /// For adding classes, functions or modules, prefer to use [`PyModuleMethods::add_class`],
237    /// [`PyModuleMethods::add_function`] or [`PyModuleMethods::add_submodule`] instead,
238    /// respectively.
239    ///
240    /// # Examples
241    ///
242    /// ```rust,no_run
243    /// use pyo3::prelude::*;
244    ///
245    /// #[pymodule]
246    /// # #[pyo3(name = "example_module_add_constant")]
247    /// fn my_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
248    ///     module.add("c", 299_792_458)?;
249    ///     Ok(())
250    /// }
251    /// ```
252    ///
253    /// Python code can then do the following:
254    ///
255    /// ```python
256    /// from my_module import c
257    ///
258    /// print("c is", c)
259    /// ```
260    ///
261    /// This will result in the following output:
262    ///
263    /// ```text
264    /// c is 299792458
265    /// ```
266    fn add<N, V>(&self, name: N, value: V) -> PyResult<()>
267    where
268        N: IntoPyObject<'py, Target = PyString>,
269        V: IntoPyObject<'py>;
270
271    /// Adds a new class to the module.
272    ///
273    /// Notice that this method does not take an argument.
274    /// Instead, this method is *generic*, and requires us to use the
275    /// "turbofish" syntax to specify the class we want to add.
276    ///
277    /// # Examples
278    ///
279    /// ```rust,no_run
280    /// use pyo3::prelude::*;
281    ///
282    /// #[pyclass]
283    /// struct Foo { /* fields omitted */ }
284    ///
285    /// #[pymodule]
286    /// # #[pyo3(name = "example_module_add_class")]
287    /// fn my_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
288    ///     module.add_class::<Foo>()?;
289    ///     Ok(())
290    /// }
291    ///  ```
292    ///
293    /// Python code can see this class as such:
294    /// ```python
295    /// from my_module import Foo
296    ///
297    /// print("Foo is", Foo)
298    /// ```
299    ///
300    /// This will result in the following output:
301    /// ```text
302    /// Foo is <class 'builtins.Foo'>
303    /// ```
304    ///
305    /// Note that as we haven't defined a [constructor][1], Python code can't actually
306    /// make an *instance* of `Foo` (or *get* one for that matter, as we haven't exported
307    /// anything that can return instances of `Foo`).
308    ///
309    #[doc = concat!("[1]: https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/class.html#constructor")]
310    fn add_class<T>(&self) -> PyResult<()>
311    where
312        T: PyClass;
313
314    /// Adds a function or a (sub)module to a module, using the functions name as name.
315    ///
316    /// Prefer to use [`PyModuleMethods::add_function`] and/or [`PyModuleMethods::add_submodule`]
317    /// instead.
318    fn add_wrapped<T>(&self, wrapper: &impl Fn(Python<'py>) -> T) -> PyResult<()>
319    where
320        T: IntoPyCallbackOutput<'py, Py<PyAny>>;
321
322    /// Adds a submodule to a module.
323    ///
324    /// This is especially useful for creating module hierarchies.
325    ///
326    /// Note that this doesn't define a *package*, so this won't allow Python code
327    /// to directly import submodules by using
328    /// <span style="white-space: pre">`from my_module import submodule`</span>.
329    /// For more information, see [#759][1] and [#1517][2].
330    ///
331    /// # Examples
332    ///
333    /// ```rust,no_run
334    /// use pyo3::prelude::*;
335    ///
336    /// #[pymodule]
337    /// # #[pyo3(name = "example_module_add_submodule")]
338    /// fn my_module(py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> {
339    ///     let submodule = PyModule::new(py, "submodule")?;
340    ///     submodule.add("super_useful_constant", "important")?;
341    ///
342    ///     module.add_submodule(&submodule)?;
343    ///     Ok(())
344    /// }
345    /// ```
346    ///
347    /// Python code can then do the following:
348    ///
349    /// ```python
350    /// import my_module
351    ///
352    /// print("super_useful_constant is", my_module.submodule.super_useful_constant)
353    /// ```
354    ///
355    /// This will result in the following output:
356    ///
357    /// ```text
358    /// super_useful_constant is important
359    /// ```
360    ///
361    /// [1]: https://github.com/PyO3/pyo3/issues/759
362    /// [2]: https://github.com/PyO3/pyo3/issues/1517#issuecomment-808664021
363    fn add_submodule(&self, module: &Bound<'_, PyModule>) -> PyResult<()>;
364
365    /// Add a function to a module.
366    ///
367    /// Note that this also requires the [`wrap_pyfunction!`][2] macro
368    /// to wrap a function annotated with [`#[pyfunction]`][1].
369    ///
370    /// ```rust,no_run
371    /// use pyo3::prelude::*;
372    ///
373    /// #[pyfunction]
374    /// fn say_hello() {
375    ///     println!("Hello world!")
376    /// }
377    /// #[pymodule]
378    /// # #[pyo3(name = "example_module_add_function")]
379    /// fn my_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
380    ///     module.add_function(wrap_pyfunction!(say_hello, module)?)
381    /// }
382    /// ```
383    ///
384    /// Python code can then do the following:
385    ///
386    /// ```python
387    /// from my_module import say_hello
388    ///
389    /// say_hello()
390    /// ```
391    ///
392    /// This will result in the following output:
393    ///
394    /// ```text
395    /// Hello world!
396    /// ```
397    ///
398    /// [1]: crate::prelude::pyfunction
399    /// [2]: crate::wrap_pyfunction
400    fn add_function(&self, fun: Bound<'_, PyCFunction>) -> PyResult<()>;
401
402    /// Declare whether or not this module supports running with the GIL disabled
403    ///
404    /// Since PyO3 0.28, PyO3 defaults to assuming that modules do not require the
405    /// GIL for thread safety. Call this function with `true` to opt-out of supporting
406    /// free-threaded Python.
407    ///
408    /// This function sets the [`Py_MOD_GIL`
409    /// slot](https://docs.python.org/3/c-api/module.html#c.Py_mod_gil) on the
410    /// module object.
411    ///
412    /// # Examples
413    ///
414    /// ```rust,no_run
415    /// use pyo3::prelude::*;
416    ///
417    /// #[pymodule]
418    /// # #[pyo3(name = "example_module_gil_used")]
419    /// fn my_module(py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> {
420    ///     let submodule = PyModule::new(py, "submodule")?;
421    ///     submodule.gil_used(true)?;
422    ///     module.add_submodule(&submodule)?;
423    ///     Ok(())
424    /// }
425    /// ```
426    ///
427    /// The resulting module will print a `RuntimeWarning` and re-enable the
428    /// GIL when Python imports it on the free-threaded build.
429    ///
430    /// This is a no-op on the GIL-enabled build.
431    fn gil_used(&self, gil_used: bool) -> PyResult<()>;
432}
433
434impl<'py> PyModuleMethods<'py> for Bound<'py, PyModule> {
435    fn dict(&self) -> Bound<'py, PyDict> {
436        unsafe {
437            // PyModule_GetDict returns borrowed ptr; must make owned for safety (see #890).
438            ffi::PyModule_GetDict(self.as_ptr())
439                .assume_borrowed(self.py())
440                .to_owned()
441                .cast_into_unchecked()
442        }
443    }
444
445    fn index(&self) -> PyResult<Bound<'py, PyList>> {
446        let __all__ = __all__(self.py());
447        match self.getattr(__all__) {
448            Ok(idx) => idx.cast_into().map_err(PyErr::from),
449            Err(err) => {
450                if err.is_instance_of::<exceptions::PyAttributeError>(self.py()) {
451                    let l = PyList::empty(self.py());
452                    self.setattr(__all__, &l)?;
453                    Ok(l)
454                } else {
455                    Err(err)
456                }
457            }
458        }
459    }
460
461    fn name(&self) -> PyResult<Bound<'py, PyString>> {
462        #[cfg(not(PyPy))]
463        {
464            unsafe {
465                ffi::PyModule_GetNameObject(self.as_ptr())
466                    .assume_owned_or_err(self.py())
467                    .cast_into_unchecked()
468            }
469        }
470
471        #[cfg(PyPy)]
472        {
473            self.dict()
474                .get_item("__name__")
475                .map_err(|_| exceptions::PyAttributeError::new_err("__name__"))?
476                .cast_into()
477                .map_err(PyErr::from)
478        }
479    }
480
481    fn filename(&self) -> PyResult<Bound<'py, PyString>> {
482        #[cfg(not(PyPy))]
483        unsafe {
484            ffi::PyModule_GetFilenameObject(self.as_ptr())
485                .assume_owned_or_err(self.py())
486                .cast_into_unchecked()
487        }
488
489        #[cfg(PyPy)]
490        {
491            self.dict()
492                .get_item("__file__")
493                .map_err(|_| exceptions::PyAttributeError::new_err("__file__"))?
494                .cast_into()
495                .map_err(PyErr::from)
496        }
497    }
498
499    fn add<N, V>(&self, name: N, value: V) -> PyResult<()>
500    where
501        N: IntoPyObject<'py, Target = PyString>,
502        V: IntoPyObject<'py>,
503    {
504        fn inner(
505            module: &Bound<'_, PyModule>,
506            name: Borrowed<'_, '_, PyString>,
507            value: Borrowed<'_, '_, PyAny>,
508        ) -> PyResult<()> {
509            module
510                .index()?
511                .append(name)
512                .expect("could not append __name__ to __all__");
513            module.setattr(name, value)
514        }
515
516        let py = self.py();
517        inner(
518            self,
519            name.into_pyobject_or_pyerr(py)?.as_borrowed(),
520            value.into_pyobject_or_pyerr(py)?.into_any().as_borrowed(),
521        )
522    }
523
524    fn add_class<T>(&self) -> PyResult<()>
525    where
526        T: PyClass,
527    {
528        let py = self.py();
529        self.add(
530            <T as PyClass>::NAME,
531            T::lazy_type_object().get_or_try_init(py)?,
532        )
533    }
534
535    fn add_wrapped<T>(&self, wrapper: &impl Fn(Python<'py>) -> T) -> PyResult<()>
536    where
537        T: IntoPyCallbackOutput<'py, Py<PyAny>>,
538    {
539        fn inner(module: &Bound<'_, PyModule>, object: Bound<'_, PyAny>) -> PyResult<()> {
540            let name = object.getattr(__name__(module.py()))?;
541            module.add(name.cast_into::<PyString>()?, object)
542        }
543
544        let py = self.py();
545        inner(self, wrapper(py).convert(py)?.into_bound(py))
546    }
547
548    fn add_submodule(&self, module: &Bound<'_, PyModule>) -> PyResult<()> {
549        let name = module.name()?;
550        let name = name.to_cow()?;
551        let name = match name.rsplit_once('.') {
552            Some((_, name)) => Cow::from(name),
553            None => name,
554        };
555        self.add(name, module)
556    }
557
558    fn add_function(&self, fun: Bound<'_, PyCFunction>) -> PyResult<()> {
559        let name = fun.getattr(__name__(self.py()))?;
560        self.add(name.cast_into::<PyString>()?, fun)
561    }
562
563    #[cfg_attr(any(Py_LIMITED_API, not(Py_GIL_DISABLED)), allow(unused_variables))]
564    fn gil_used(&self, gil_used: bool) -> PyResult<()> {
565        #[cfg(all(not(Py_LIMITED_API), Py_GIL_DISABLED))]
566        {
567            let gil_used = match gil_used {
568                true => ffi::Py_MOD_GIL_USED,
569                false => ffi::Py_MOD_GIL_NOT_USED,
570            };
571            match unsafe { ffi::PyUnstable_Module_SetGIL(self.as_ptr(), gil_used) } {
572                c_int::MIN..=-1 => Err(PyErr::fetch(self.py())),
573                0..=c_int::MAX => Ok(()),
574            }
575        }
576        #[cfg(any(Py_LIMITED_API, not(Py_GIL_DISABLED)))]
577        Ok(())
578    }
579}
580
581fn __all__(py: Python<'_>) -> &Bound<'_, PyString> {
582    intern!(py, "__all__")
583}
584
585fn __name__(py: Python<'_>) -> &Bound<'_, PyString> {
586    intern!(py, "__name__")
587}
588
589#[cfg(test)]
590mod tests {
591    use crate::{
592        Python,
593        types::{PyModule, module::PyModuleMethods},
594    };
595
596    #[test]
597    fn module_import_and_name() {
598        Python::attach(|py| {
599            let builtins = PyModule::import(py, "builtins").unwrap();
600            assert_eq!(builtins.name().unwrap(), "builtins");
601        })
602    }
603
604    #[test]
605    fn module_filename() {
606        use crate::types::string::PyStringMethods;
607        Python::attach(|py| {
608            let site = PyModule::import(py, "site").unwrap();
609            assert!(
610                site.filename()
611                    .unwrap()
612                    .to_cow()
613                    .unwrap()
614                    .ends_with("site.py")
615            );
616        })
617    }
618
619    #[test]
620    fn module_from_code_empty_file() {
621        Python::attach(|py| {
622            let builtins = PyModule::from_code(py, c"", c"", c"").unwrap();
623            assert_eq!(builtins.filename().unwrap(), "<string>");
624        })
625    }
626}