Add documentation for accessing PyModule in #[pyfunction]s.

This commit is contained in:
Sebastian Pütz 2020-09-04 10:02:40 +02:00
parent 4aae523e54
commit 9137855e81
1 changed files with 50 additions and 0 deletions

View File

@ -189,3 +189,53 @@ If you have a static function, you can expose it with `#[pyfunction]` and use [`
[`PyAny::call1`]: https://docs.rs/pyo3/latest/pyo3/struct.PyAny.html#tymethod.call1
[`PyObject`]: https://docs.rs/pyo3/latest/pyo3/type.PyObject.html
[`wrap_pyfunction!`]: https://docs.rs/pyo3/latest/pyo3/macro.wrap_pyfunction.html
### Accessing the module of a function
Functions are usually associated with modules, in the C-API, the self parameter in a function call corresponds
to the module of the function. It is possible to access the module of a `#[pyfunction]` and `#[pyfn]` in the
function body by passing the `need_module` argument to the attribute:
```rust
use pyo3::wrap_pyfunction;
use pyo3::prelude::*;
#[pyfunction(need_module)]
fn pyfunction_with_module(
module: &PyModule
) -> PyResult<&str> {
module.name()
}
#[pymodule]
fn module_with_fn(py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(pyfunction_with_module))
}
# fn main() {}
```
If `need_module` is set, the first argument **must** be the `&PyModule`. It is then possible to interact with
the module.
The same works for `#[pyfn]`:
```rust
use pyo3::wrap_pyfunction;
use pyo3::prelude::*;
#[pymodule]
fn module_with_fn(py: Python, m: &PyModule) -> PyResult<()> {
#[pyfn(m, "module_name", need_module)]
fn module_name(module: &PyModule) -> PyResult<&str> {
module.name()
}
Ok(())
}
# fn main() {}
```
Within Python, the name of the module that a function belongs to can be accessed through the `__module__`
attribute.