Crate cpython [] [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.

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.

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

extern crate cpython;

use cpython::{PythonObject, Python};
use cpython::ObjectProtocol; //for call method

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python(); // obtain `Python` token

    let sys = py.import("sys").unwrap();
    let version: String = sys.get(py, "version").unwrap().extract(py).unwrap();

    let os = py.import("os").unwrap();
    let getenv = os.get(py, "getenv").unwrap();
    let user: String = getenv.call(py, ("USER",), None).unwrap().extract(py).unwrap();

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

Modules

argparse

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

exc

This module contains the python exception types.

Macros

py_argparse!

This macro is used to parse a parameter list into a set of variables.

py_class_method!

Creates a Python class method descriptor that invokes a Rust function.

py_fn!

Creates a Python callable object that invokes a Rust function.

py_method!

Creates a Python instance method descriptor that invokes a Rust function. There are two forms of this macro: 1) py_method!(f) f is the name of a rust function with the signature fn(Python, &SelfType, &PyTuple, Option<&PyDict>) -> PyResult<R> for some R that implements ToPyObject.

py_module_initializer!

Structs

GILGuard

RAII type that represents the Global Interpreter Lock acquisition.

GILProtected

Mutex-like wrapper object for data that is protected by the Python GIL.

NoArgs

An empty struct that represents the empty argument list. Corresponds to the empty tuple () in Python.

PyBool

Represents a Python bool.

PyBytes

Represents a Python byte string. Corresponds to str in Python 2, and bytes in Python 3.

PyDict

Represents a Python dict.

PyErr

Represents a Python exception that was raised.

PyFloat

Represents a Python float object.

PyInt

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.

PyIterator

A python iterator object.

PyList

Represents a Python list.

PyLong

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.

PyModule

Represents a Python module object.

PyObject

Represents a reference to a Python object.

PyRustObject

A Python object that contains a rust value of type T, and is derived from base class B. Note that this type effectively acts like Rc<T>, except that the reference counting is done by the Python runtime.

PyRustType

A Python class that contains rust values of type T. Serves as a Python type object, and can be used to construct PyRustObject<T> instances.

PyRustTypeBuilder
PySequence

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

PyString

Represents a Python unicode string. Corresponds to unicode in Python 2, and str in Python 3.

PyTuple

Represents a Python tuple object.

PyType

Represents a reference to a Python type object.

PyUnicode

Represents a Python unicode string. Corresponds to unicode in Python 2, and str in Python 3.

Python

Marker type that indicates that the GIL is currently held.

Traits

ExtractPyObject

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

ObjectProtocol

Trait that contains methods

PyClone
PyDrop
PythonObject

Trait implemented by all Python object types.

PythonObjectWithCheckedDowncast

Trait implemented by Python object types that allow a checked downcast.

PythonObjectWithTypeObject

Trait implemented by Python object types that have a corresponding type object.

ToPyObject

Conversion trait that allows various objects to be converted into 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.

Py_hash_t
Py_ssize_t