Expand description

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.

The method clone_ref() (from trait PyClone) can be used to create additional references to the same 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.

Python 2.7

The library will use the python3 bindings by default. To use the python2 bindings you must specific the python27 feature explicitly in your Cargo.toml.

[dependencies.cpython]
version = "*"
default-features = false
features = ["python27-sys"]

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 rust-cpython library are also exposed as Python exceptions.

Example

use cpython::{Python, PyDict, PyResult};

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(py, "version")?.extract(py)?;

    let locals = PyDict::new(py);
    locals.set_item(py, "os", py.import("os")?)?;
    let user: String = py.eval("os.getenv('USER') or os.getenv('USERNAME')", None, Some(&locals))?.extract(py)?;

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

Re-exports

pub use crate::py_class::CompareOp;

Modules

This module contains logic for parsing a python argument list. See also the macros py_argparse!, py_fn! and py_method!.
This module contains the python exception types.

Macros

This macro is used to parse a parameter list into a set of variables.
Macro to retrieve a Python capsule pointing to an array of data, with a layer of caching.
Macro to retrieve a function pointer capsule.
Defines new python extension class. A py_class! macro invocation generates code that declares a new Python class. Additionally, it generates a Rust struct of the same name, which allows accessing instances of that Python class from Rust.
Defines a new exception type.
Creates a Python callable object that invokes a Rust function.

Structs

RAII type that represents the Global Interpreter Lock acquisition.
Mutex-like wrapper object for data that is protected by the Python GIL.
An empty struct that represents the empty argument list. Corresponds to the empty tuple () in Python.
Represents a Python bool.
Represents a Python byte string. Corresponds to str in Python 2, and bytes in Python 3.
Capsules are the preferred way to export/import C APIs between extension modules, see Providing a C API for an Extension Module.
Represents a Python dict.
Represents a Python exception that was raised.
Represents a Python float object.
In Python 2.x, represents a Python long object. In Python 3.x, represents a Python int object. Both PyInt and PyLong refer to the same type on Python 3.x.
A python iterator object.
An immutably borrowed reference to a leaked value.
A mutably borrowed reference to a leaked value.
Represents a Python list.
In Python 2.x, represents a Python long object. In Python 3.x, represents a Python int object. Both PyInt and PyLong refer to the same type on Python 3.x.
Represents a Python module object.
An empty struct that represents None in Python.
Represents a reference to a Python object.
Represents a reference to a python object supporting the sequence protocol.
Represents a Python set.
A reference to PySharedRefCell owned by a Python object.
A mutable memory location shareable immutably across Python objects.
Represents a Python string. Corresponds to basestring in Python 2, and str in Python 3.
Represents a Python tuple object.
Represents a reference to a Python type object.
Represents a Python string. Corresponds to basestring in Python 2, and str in Python 3.
Marker type that indicates that the GIL is currently held.
An immutable reference to PySharedRefCell value, not bound to lifetime.

Enums

Enum of possible Python string representations.

Traits

FromPyObject is implemented by various types that can be extracted from a Python object.
Operations on numeric objects
Trait that contains methods
Trait implemented by all Python object types.
Trait implemented by Python object types that allow a checked downcast.
Trait implemented by Python object types that have a corresponding type object.
RefFromPyObject is implemented by various types that can be extracted as a reference from a Python object. Depending on the input object, the reference may point into memory owned by the Python interpreter; or into a temporary object.
Conversion trait that allows various objects to be converted into Python objects.

Functions

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

Type Definitions

Represents the result of a Python call.