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)]

  1. name: The module name as a Rust identifier
  2. 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.

  1. m: The module name.
  2. name of function visible to Python code.
  3. 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

PyBuffer implementation

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 PyO3 Prelude

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 () in Python.

Py

Safe wrapper around unsafe *mut ffi::PyObject pointer with specified type information.

PyBool

Represents a Python bool.

PyByteArray

Represents a Python bytearray.

PyBytes

Represents a Python byte string.

PyDict

Represents a Python dict.

PyDowncastError

Marker type that indicates an error while downcasting

PyErr

Represents a Python exception that was raised.

PyFloat

Represents a Python float object.

PyFrozenSet

Represents a Python frozenset

PyInt

Represents a Python int object.

PyIterator

A python iterator object.

PyList

Represents a Python list.

PyLong

Represents a Python int object.

PyModule

Represents a Python module object.

PyObject

Safe wrapper around unsafe *mut ffi::PyObject pointer.

PyObjectRef

Represents general python instance.

PySequence

Represents a reference to a python object supporting the sequence protocol.

PySet

Represents a Python set

PySlice

Represents a Python slice.

PySliceIndices

Represents a Python slice indices

PyString

Represents a Python string.

PyToken
PyTuple

Represents a Python tuple object.

PyType

Represents a reference to a Python type object.

Python

Marker type that indicates that the GIL is currently held.

Enums

PyErrValue

Represents a PyErr value

PyStringData

Enum of possible Python string representations.

Traits

AsPyRef

Trait implements objet reference extraction from python managed pointer.

FromPyObject

FromPyObject is implemented by various types that can be extracted from a Python object reference.

IntoPyDictPointer

Conversion trait that allows various objects to be converted into PyDict object pointer. Primary use case for this trait is call and call_method methods as keywords argument.

IntoPyObject

Conversion trait that allows various objects to be converted into PyObject by consuming original object.

IntoPyPointer

This trait allows retrieving the underlying FFI pointer from Python objects.

IntoPyTuple

Conversion trait that allows various objects to be converted into PyTuple object.

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 gil.

PyTryFrom

Trait implemented by Python object types that allow a checked downcast. This trait is similar to std::convert::TryFrom

PyTryInto

Trait implemented by Python object types that allow a checked downcast. This trait is similar to std::convert::TryInto

RefFromPyObject
ToBorrowedObject
ToPyObject

Conversion trait that allows various objects to be converted into PyObject

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.