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§
- argparse
- This module contains logic for parsing a python argument list.
See also the macros
py_argparse!
,py_fn!
andpy_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_
capsule - Macro to retrieve a Python capsule pointing to an array of data, with a layer of caching.
- py_
capsule_ fn - Macro to retrieve a function pointer capsule.
- 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, andbytes
in Python 3. - PyCapsule
- Capsules are the preferred way to export/import C APIs between extension modules, see Providing a C API for an Extension Module.
- 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 Pythonint
object. BothPyInt
andPyLong
refer to the same type on Python 3.x. - PyIterator
- A python iterator object.
- PyLeaked
Ref - An immutably borrowed reference to a leaked value.
- PyLeaked
RefMut - A mutably borrowed reference to a leaked value.
- PyList
- Represents a Python
list
. - PyLong
- In Python 2.x, represents a Python
long
object. In Python 3.x, represents a Pythonint
object. BothPyInt
andPyLong
refer to the same type on Python 3.x. - PyModule
- Represents a Python module object.
- PyNone
- An empty struct that represents
None
in Python. - PyObject
- Represents a reference to a Python object.
- PySequence
- Represents a reference to a python object supporting the sequence protocol.
- PySet
- Represents a Python
set
. - PyShared
Ref - A reference to
PySharedRefCell
owned by a Python object. - PyShared
RefCell - A mutable memory location shareable immutably across Python objects.
- PyString
- Represents a Python string.
Corresponds to
basestring
in Python 2, andstr
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, andstr
in Python 3. - Python
- Marker type that indicates that the GIL is currently held.
- Python
Object Downcast Error - Unsafe
PyLeaked - An immutable reference to
PySharedRefCell
value, not bound to lifetime.
Enums§
- PyString
Data - Enum of possible Python string representations.
Traits§
- From
PyObject - FromPyObject is implemented by various types that can be extracted from a Python object.
- Number
Protocol - Operations on numeric objects
- Object
Protocol - Trait that contains methods
- PyClone
- PyDrop
- Python
Object - Trait implemented by all Python object types.
- Python
Object With Checked Downcast - Trait implemented by Python object types that allow a checked downcast.
- Python
Object With Type Object - Trait implemented by Python object types that have a corresponding type object.
- RefFrom
PyObject - 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.
- ToPy
Object - 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 Aliases§
- PyResult
- Represents the result of a Python call.
- Py_
hash_ t - Py_
ssize_ t