[][src]Crate pyo3

Rust bindings to the Python interpreter.

Look at the guide for a detailed introduction.

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

Using rust from python

Pyo3 can be used to generate a native python module.

Cargo.toml

[package]
name = "string-sum"
version = "0.1.0"
edition = "2018"

[lib]
name = "string_sum"
crate-type = ["cdylib"]

[dependencies.pyo3]
version = "0.8.4"
features = ["extension-module"]

src/lib.rs

use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

#[pyfunction]
/// Formats the sum of two numbers as string
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
    Ok((a + b).to_string())
}

/// This module is a python module implemented in Rust.
#[pymodule]
fn string_sum(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pyfunction!(sum_as_string))?;

    Ok(())
}

On windows and linux, you can build normally with cargo build --release. On macOS, you need to set additional linker arguments. One option is to compile with cargo rustc --release -- -C link-arg=-undefined -C link-arg=dynamic_lookup, the other is to create a .cargo/config with the following content:

[target.x86_64-apple-darwin]
rustflags = [
  "-C", "link-arg=-undefined",
  "-C", "link-arg=dynamic_lookup",
]

For developing, you can copy and rename the shared library from the target folder: On macOS, rename libstring_sum.dylib to string_sum.so, on windows libstring_sum.dll to string_sum.pyd and on linux libstring_sum.so to string_sum.so. Then open a python shell in the same folder and you'll be able to import string_sum.

To build, test and publish your crate as python module, you can use maturin or setuptools-rust. You can find an example for setuptools-rust in examples/word-count, while maturin should work on your crate without any configuration.

Using python from rust

Add pyo3 this to your Cargo.toml:

[dependencies]
pyo3 = "0.8.4"

Example program displaying the value of sys.version:

use pyo3::prelude::*;
use pyo3::types::IntoPyDict;

fn main() -> PyResult<()> {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let sys = py.import("sys")?;
    let version: String = sys.get("version")?.extract()?;

    let locals = [("os", py.import("os")?)].into_py_dict(py);
    let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
    let user: String = py.eval(code, None, Some(&locals))?.extract()?;

    println!("Hello {}, I'm Python {}", user, version);
    Ok(())
}

Re-exports

pub use crate::class::*;
pub use crate::type_object::PyObjectAlloc;
pub use crate::type_object::PyRawObject;
pub use crate::type_object::PyTypeInfo;

Modules

buffer

PyBuffer implementation

class

Python object protocols

exceptions

Exception types defined by python.

ffi

Raw ffi declarations for the c interface of python

freelist

Free allocation list

marshal
prelude

A collection of items you most likely want to have in scope when working with pyo3

proc_macro

The proc macros, which are also part of the prelude

type_object

Python type object information

types

Various types defined by the python interpreter such as int, str and tuple

Macros

create_exception

Defines a new exception type.

create_exception_type_object

impl $crate::type_object::PyTypeObject for $name where $name is an exception newly defined in rust code.

impl_exception_boilerplate

The boilerplate to convert between a rust type and a python exception

import_exception

Defines rust type for exception defined in Python code.

import_exception_type_object

impl $crate::type_object::PyTypeObject for $name where $name is an exception defined in python code.

py_run

A convenient macro to execute a Python code snippet, with some local variables set.

pyobject_downcast

Implements a typesafe conversions throught FromPyObject, given a typecheck function as second parameter

pyobject_native_type
pyobject_native_type_convert
pyobject_native_type_named
wrap_pyfunction

Returns a function that takes a Python instance and returns a python function.

wrap_pymodule

Returns a function that takes a Python instance and returns a python module.

Structs

GILGuard

RAII type that represents the Global Interpreter Lock acquisition.

ManagedPyRef

Reference to a converted ToPyObject.

Py

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

PyDowncastError

Marker type that indicates an error while downcasting

PyErr

Represents a Python exception that was raised.

PyObject

A python object

PyRef

A special reference of type T. PyRef<T> refers a instance of T, which exists in the Python heap as a part of a Python object.

PyRefMut

Mutable version of PyRef.

Python

Marker type that indicates that the GIL is currently held.

Enums

PyErrValue

Represents a PyErr value

Traits

AsPyPointer

This trait represents that, we can do zero-cost conversion from the object to FFI pointer.

AsPyRef

Trait implements object reference extraction from python managed pointer.

FromPy

Similar to std::convert::From, just that it requires a gil token.

FromPyObject

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

FromPyPointer

Raw level conversion between *mut ffi::PyObject and PyO3 types.

IntoPy

Similar to std::convert::Into, just that it requires a gil token.

IntoPyPointer

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

ObjectProtocol

Python object model helper methods

PyErrArguments

Helper conversion trait that allows to use custom arguments for exception constructor.

PyNativeType

Types that are built into the python interpreter.

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

ToBorrowedObject

This trait has two implementations: The slow one is implemented for all ToPyObject and creates a new object using ToPyObject::to_object, while the fast one is only implemented for AsPyPointer (we know that every AsPyPointer is also ToPyObject) and uses AsPyPointer::as_ptr()

ToPyObject

Conversion trait that allows various objects to be converted into PyObject

Functions

prepare_freethreaded_python

Prepares the use of Python in a free-threaded context.

Type Definitions

PyResult

Represents the result of a Python call.