Crate pyo3 [−] [src]
Rust bindings to the Python interpreter.
Ownership and Lifetimes
In Python, all objects are implicitly reference counted.
In rust, we will use the PyObject
type to represent a reference to a Python object.
Because all Python objects potentially have multiple owners, the concept of Rust mutability does not apply to Python objects. As a result, this API will allow mutating Python objects even if they are not stored in a mutable Rust variable.
The Python interpreter uses a global interpreter lock (GIL)
to ensure thread-safety.
This API uses a zero-sized struct Python<'p>
as a token to indicate
that a function can assume that the GIL is held.
You obtain a Python
instance by acquiring the GIL,
and have to pass it into all operations that call into the Python runtime.
Error Handling
The vast majority of operations in this library will return PyResult<...>
.
This is an alias for the type Result<..., PyErr>
.
A PyErr
represents a Python exception. Errors within the PyO3
library are
also exposed as Python exceptions.
Example
extern crate pyo3; use pyo3::{Python, PyDict, PyResult, ObjectProtocol}; fn main() { let gil = Python::acquire_gil(); hello(gil.python()).unwrap(); } fn hello(py: Python) -> PyResult<()> { let sys = py.import("sys")?; let version: String = sys.get("version")?.extract()?; let locals = PyDict::new(py); locals.set_item("os", py.import("os")?)?; let user: String = py.eval("os.getenv('USER') or os.getenv('USERNAME')", None, Some(locals))?.extract()?; println!("Hello {}, I'm Python {}", user, version); Ok(()) }
Python extension
To allow Python to load the rust code as a Python extension
module, you need provide initialization function and annotate it with #[py::modinit(name)]
.
py::modinit
expands to an extern "C"
function.
Macro syntax: #[py::modinit(name)]
name
: The module name as a Rust identifier- Decorate init function
Fn(Python, &PyModule) -> PyResult<()>
. This function will be called when the module is imported, and is responsible for adding the module's members.
To creates a Python callable object that invokes a Rust function, specify rust
function and decorate it with #[pyfn()]
attribute. pyfn()
accepts three parameters.
m
: The module name.- name of function visible to Python code.
- comma separated arguments, i.e. param="None", "*", param3="55"
Example
#![feature(proc_macro, specialization)] extern crate pyo3; use pyo3::{py, Python, PyResult, PyModule, PyString}; // add bindings to the generated python module // N.B: names: "libhello" must be the name of the `.so` or `.pyd` file /// Module documentation string #[py::modinit(hello)] fn init_module(py: Python, m: &PyModule) -> PyResult<()> { // pyo3 aware function. All of our python interface could be declared // in a separate module. // Note that the `#[pyfn()]` annotation automatically converts the arguments from // Python objects to Rust values; and the Rust return value back into a Python object. #[pyfn(m, "run_rust_func")] fn run(name: &PyString) -> PyResult<()> { println!("Rust says: Hello {} of Python!", name); Ok(()) } Ok(()) }
In your Cargo.toml
, use the extension-module
feature for the pyo3
dependency:
[dependencies.pyo3]
version = "*"
features = ["extension-module"]
The full example project can be found at: https://github.com/PyO3/setuptools-rust/tree/master/example/
Rust will compile the code into a file named libhello.so
, but we have to
rename the file in order to use it with Python:
cp ./target/debug/libhello.so ./hello.so
(Note: on macOS you will have to rename libhello.dynlib
to libhello.so
)
The extension module can then be imported into Python:
>>> import hello
>>> hello.run_rust_func("test")
Rust says: Hello Python!
Reexports
pub use typeob::PyTypeInfo; |
pub use typeob::PyRawObject; |
pub use typeob::PyObjectAlloc; |
pub use class::*; |
Modules
buffer |
|
class |
Python object protocols |
exc |
This module contains the standard python exception types. |
ffi |
Rust FFI declarations for Python |
freelist |
Free allocation list |
prelude |
The |
py |
Procedural macros |
typeob |
Python type object information |
Macros
import_exception |
Defines rust type for exception defined in Python code. |
py_exception |
Defines a new exception type. |
Structs
GILGuard |
RAII type that represents the Global Interpreter Lock acquisition. |
NoArgs |
An empty struct that represents the empty argument list.
Corresponds to the empty tuple |
Py |
Safe wrapper around unsafe |
PyBool |
Represents a Python |
PyByteArray |
Represents a Python |
PyBytes |
Represents a Python |
PyDict |
Represents a Python |
PyDowncastError |
Marker type that indicates an error while downcasting |
PyErr |
Represents a Python exception that was raised. |
PyFloat |
Represents a Python |
PyFrozenSet |
Represents a Python |
PyInt |
Represents a Python |
PyIterator |
A python iterator object. |
PyList |
Represents a Python |
PyLong |
Represents a Python |
PyModule |
Represents a Python |
PyObject |
Safe wrapper around unsafe |
PyObjectRef |
Represents general python instance. |
PySequence |
Represents a reference to a python object supporting the sequence protocol. |
PySet |
Represents a Python |
PySlice |
Represents a Python |
PySliceIndices |
Represents a Python |
PyString |
Represents a Python |
PyToken | |
PyTuple |
Represents a Python |
PyType |
Represents a reference to a Python |
Python |
Marker type that indicates that the GIL is currently held. |
Enums
PyErrValue |
Represents a |
PyStringData |
Enum of possible Python string representations. |
Traits
AsPyRef |
Trait implements objet reference extraction from python managed pointer. |
FromPyObject |
|
IntoPyDictPointer |
Conversion trait that allows various objects to be converted into |
IntoPyObject |
Conversion trait that allows various objects to be converted into |
IntoPyPointer |
This trait allows retrieving the underlying FFI pointer from Python objects. |
IntoPyTuple |
Conversion trait that allows various objects to be converted into |
ObjectProtocol |
Python object model helper methods |
PyErrArguments |
Helper conversion trait that allows to use custom arguments for exception constructor. |
PyObjectWithToken |
Any instance that is managed Python can have access to |
PyTryFrom |
Trait implemented by Python object types that allow a checked downcast.
This trait is similar to |
PyTryInto |
Trait implemented by Python object types that allow a checked downcast.
This trait is similar to |
RefFromPyObject | |
ToBorrowedObject | |
ToPyObject |
Conversion trait that allows various objects to be converted into |
ToPyPointer |
This trait allows retrieving the underlying FFI pointer from Python objects. |
Functions
prepare_freethreaded_python |
Prepares the use of Python in a free-threaded context. |
Type Definitions
PyResult |
Represents the result of a Python call. |