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::{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(())
}

Reexports

pub use py_class::CompareOp;

Modules

argparse

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

buffer
exc

This module contains the python exception types.

py_class

Macros

py_argparse

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

py_class

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.

py_exception

Defines a new exception type.

py_fn

Creates a Python callable object that invokes a Rust function.

py_module_initializer
pyobject_newtype

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.

PySequence

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

PyString

Represents a Python string. Corresponds to basestring 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 string. Corresponds to basestring in Python 2, and str in Python 3.

Python

Marker type that indicates that the GIL is currently held.

PythonObjectDowncastError

Enums

PyStringData

Enum of possible Python string representations.

Traits

FromPyObject

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.

RefFromPyObject
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