Expand description
Raw FFI declarations for Python’s C API.
PyO3 can be used to write native Python modules or run Python code and modules from Rust.
This crate just provides low level bindings to the Python interpreter. It is meant for advanced users only - regular PyO3 users shouldn’t need to interact with this crate at all.
The contents of this crate are not documented here, as it would entail basically copying the documentation from CPython. Consult the Python/C API Reference Manual for up-to-date documentation.
§Safety
The functions in this crate lack individual safety documentation, but generally the following apply:
- Pointer arguments have to point to a valid Python object of the correct type, although null pointers are sometimes valid input.
- The vast majority can only be used safely while the GIL is held.
- Some functions have additional safety requirements, consult the Python/C API Reference Manual for more information.
§Feature flags
PyO3 uses feature flags to enable you to opt-in to additional functionality. For a detailed description, see the Features chapter of the guide.
§Optional feature flags
The following features customize PyO3’s behavior:
abi3: Restricts PyO3’s API to a subset of the full Python API which is guaranteed by PEP 384 to be forward-compatible with future Python versions.extension-module: This will tell the linker to keep the Python symbols unresolved, so that your module can also be used with statically linked Python interpreters. Use this feature when building an extension module.
§rustc environment flags
PyO3 uses rustc’s --cfg flags to enable or disable code used for different Python versions.
If you want to do this for your own crate, you can do so with the pyo3-build-config crate.
Py_3_7,Py_3_8,Py_3_9,Py_3_10,Py_3_11,Py_3_12,Py_3_13: Marks code that is only enabled when compiling for a given minimum Python version.Py_LIMITED_API: Marks code enabled when theabi3feature flag is enabled.Py_GIL_DISABLED: Marks code that runs only in the free-threaded build of CPython.PyPy- Marks code enabled when compiling for PyPy.GraalPy- Marks code enabled when compiling for GraalPy.
Additionally, you can query for the values Py_DEBUG, Py_REF_DEBUG,
Py_TRACE_REFS, and COUNT_ALLOCS from py_sys_config to query for the
corresponding C build-time defines. For example, to conditionally define
debug code using Py_DEBUG, you could do:
#[cfg(py_sys_config = "Py_DEBUG")]
println!("only runs if python was compiled with Py_DEBUG")To use these attributes, add pyo3-build-config as a build dependency in
your Cargo.toml:
[build-dependencies]
pyo3-build-config ="0.24.1"And then either create a new build.rs file in the project root or modify
the existing build.rs file to call use_pyo3_cfgs():
fn main() {
pyo3_build_config::use_pyo3_cfgs();
}§Minimum supported Rust and Python versions
pyo3-ffi supports the following Python distributions:
- CPython 3.7 or greater
- PyPy 7.3 (Python 3.9+)
- GraalPy 24.0 or greater (Python 3.10+)
§Example: Building Python Native modules
PyO3 can be used to generate a native Python module. The easiest way to try this out for the
first time is to use maturin. maturin is a tool for building and publishing Rust-based
Python packages with minimal configuration. The following steps set up some files for an example
Python module, install maturin, and then show how to build and import the Python module.
First, create a new folder (let’s call it string_sum) containing the following two files:
Cargo.toml
[lib]
name = "string_sum"
# "cdylib" is necessary to produce a shared library for Python to import from.
#
# Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able
# to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.:
# crate-type = ["cdylib", "rlib"]
crate-type = ["cdylib"]
[dependencies.pyo3-ffi]
version = "0.24.1"
features = ["extension-module"]
[build-dependencies]
# This is only necessary if you need to configure your build based on
# the Python version or the compile-time configuration for the interpreter.
pyo3_build_config = "0.24.1"If you need to use conditional compilation based on Python version or how
Python was compiled, you need to add pyo3-build-config as a
build-dependency in your Cargo.toml as in the example above and either
create a new build.rs file or modify an existing one so that
pyo3_build_config::use_pyo3_cfgs() gets called at build time:
build.rs
fn main() {
pyo3_build_config::use_pyo3_cfgs()
}src/lib.rs
use std::os::raw::{c_char, c_long};
use std::ptr;
use pyo3_ffi::*;
static mut MODULE_DEF: PyModuleDef = PyModuleDef {
m_base: PyModuleDef_HEAD_INIT,
m_name: c_str!("string_sum").as_ptr(),
m_doc: c_str!("A Python module written in Rust.").as_ptr(),
m_size: 0,
m_methods: unsafe { METHODS as *const [PyMethodDef] as *mut PyMethodDef },
m_slots: std::ptr::null_mut(),
m_traverse: None,
m_clear: None,
m_free: None,
};
static mut METHODS: &[PyMethodDef] = &[
PyMethodDef {
ml_name: c_str!("sum_as_string").as_ptr(),
ml_meth: PyMethodDefPointer {
PyCFunctionFast: sum_as_string,
},
ml_flags: METH_FASTCALL,
ml_doc: c_str!("returns the sum of two integers as a string").as_ptr(),
},
// A zeroed PyMethodDef to mark the end of the array.
PyMethodDef::zeroed(),
];
// The module initialization function, which must be named `PyInit_<your_module>`.
#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "C" fn PyInit_string_sum() -> *mut PyObject {
let module = PyModule_Create(ptr::addr_of_mut!(MODULE_DEF));
if module.is_null() {
return module;
}
#[cfg(Py_GIL_DISABLED)]
{
if PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED) < 0 {
Py_DECREF(module);
return std::ptr::null_mut();
}
}
module
}
/// A helper to parse function arguments
/// If we used PyO3's proc macros they'd handle all of this boilerplate for us :)
unsafe fn parse_arg_as_i32(obj: *mut PyObject, n_arg: usize) -> Option<i32> {
if PyLong_Check(obj) == 0 {
let msg = format!(
"sum_as_string expected an int for positional argument {}\0",
n_arg
);
PyErr_SetString(PyExc_TypeError, msg.as_ptr().cast::<c_char>());
return None;
}
// Let's keep the behaviour consistent on platforms where `c_long` is bigger than 32 bits.
// In particular, it is an i32 on Windows but i64 on most Linux systems
let mut overflow = 0;
let i_long: c_long = PyLong_AsLongAndOverflow(obj, &mut overflow);
#[allow(irrefutable_let_patterns)] // some platforms have c_long equal to i32
if overflow != 0 {
raise_overflowerror(obj);
None
} else if let Ok(i) = i_long.try_into() {
Some(i)
} else {
raise_overflowerror(obj);
None
}
}
unsafe fn raise_overflowerror(obj: *mut PyObject) {
let obj_repr = PyObject_Str(obj);
if !obj_repr.is_null() {
let mut size = 0;
let p = PyUnicode_AsUTF8AndSize(obj_repr, &mut size);
if !p.is_null() {
let s = std::str::from_utf8_unchecked(std::slice::from_raw_parts(
p.cast::<u8>(),
size as usize,
));
let msg = format!("cannot fit {} in 32 bits\0", s);
PyErr_SetString(PyExc_OverflowError, msg.as_ptr().cast::<c_char>());
}
Py_DECREF(obj_repr);
}
}
pub unsafe extern "C" fn sum_as_string(
_self: *mut PyObject,
args: *mut *mut PyObject,
nargs: Py_ssize_t,
) -> *mut PyObject {
if nargs != 2 {
PyErr_SetString(
PyExc_TypeError,
c_str!("sum_as_string expected 2 positional arguments").as_ptr(),
);
return std::ptr::null_mut();
}
let (first, second) = (*args, *args.add(1));
let first = match parse_arg_as_i32(first, 1) {
Some(x) => x,
None => return std::ptr::null_mut(),
};
let second = match parse_arg_as_i32(second, 2) {
Some(x) => x,
None => return std::ptr::null_mut(),
};
match first.checked_add(second) {
Some(sum) => {
let string = sum.to_string();
PyUnicode_FromStringAndSize(string.as_ptr().cast::<c_char>(), string.len() as isize)
}
None => {
PyErr_SetString(
PyExc_OverflowError,
c_str!("arguments too large to add").as_ptr(),
);
std::ptr::null_mut()
}
}
}With those two files in place, now maturin needs to be installed. This can be done using
Python’s package manager pip. First, load up a new Python virtualenv, and install maturin
into it:
$ cd string_sum
$ python -m venv .env
$ source .env/bin/activate
$ pip install maturinNow build and execute the module:
$ maturin develop
# lots of progress output as maturin runs the compilation...
$ python
>>> import string_sum
>>> string_sum.sum_as_string(5, 20)
'25'As well as with maturin, it is possible to build using setuptools-rust or
manually. Both offer more flexibility than maturin but require further
configuration.
This example stores the module definition statically and uses the PyModule_Create function
in the CPython C API to register the module. This is the “old” style for registering modules
and has the limitation that it cannot support subinterpreters. You can also create a module
using the new multi-phase initialization API that does support subinterpreters. See the
sequential project located in the examples directory at the root of the pyo3-ffi crate
for a worked example of how to this using pyo3-ffi.
§Using Python from Rust
To embed Python into a Rust binary, you need to ensure that your Python installation contains a shared library. The following steps demonstrate how to ensure this (for Ubuntu).
To install the Python shared library on Ubuntu:
sudo apt install python3-devWhile most projects use the safe wrapper provided by pyo3,
you can take a look at the orjson library as an example on how to use pyo3-ffi directly.
For those well versed in C and Rust the tutorials from the CPython documentation
can be easily converted to rust as well.
Re-exports§
pub use crate::_PyWeakReference as PyWeakReference;pub use self::marshal::*;
Modules§
- C API Compatibility Shims
- structmember
Deprecated
Macros§
- This is a helper macro to create a
&'static CStr.
Structs§
- Structure representing a
datetime.date - Structure representing a
datetime.datetime. - Structure representing a
datetime.timedelta. - Structure representing a
datetime.time. - Represents the PyGetSetDef structure.
- Represents the PyMemberDef structure.
- Represents the PyMethodDef structure.
- Structure representing a
datetime.datetimewithout atzinfomember. - Structure representing a
datetime.timewithout atzinfomember.
Enums§
Constants§
- Maximum number of dimensions
- Set if the type allows subclassing
- Objects support garbage collection (see objimp.h)
- Set if the type implements the vectorcall protocol (PEP 590)
- Set if the type object is dynamically allocated
- Set if the type is ‘ready’ – fully initialized
- Set while the type is being ‘readied’, to prevent recursive ready calls
- _Py_
T_ NONE Deprecated - _Py_
T_ OBJECT Deprecated - _Py_
WRITE_ RESTRICTED Deprecated
Statics§
- built-in ‘object’
- built-in ‘super’
- built-in ‘type’
- Py_
Bytes ⚠Warning Flag Deprecated - Py_
Debug ⚠Flag Deprecated - Py_
Dont ⚠Write Bytecode Flag Deprecated - Py_
File ⚠System Default Encode Errors Deprecated - Py_
File ⚠System Default Encoding Deprecated - Py_
Frozen ⚠Flag Deprecated - Py_
HasFile ⚠System Default Encoding Deprecated - Py_
Ignore ⚠Environment Flag Deprecated - Py_
Inspect ⚠Flag Deprecated - Py_
Interactive ⚠Flag Deprecated - Py_
Isolated ⚠Flag Deprecated - Py_
NoSite ⚠Flag Deprecated - Py_
NoUser ⚠Site Directory Deprecated - Py_
Optimize ⚠Flag Deprecated - Py_
Quiet ⚠Flag Deprecated - Py_
Unbuffered ⚠Stdio Flag Deprecated - Py_
UseClass ⚠Exceptions Flag Deprecated - Py_
Verbose ⚠Flag Deprecated
Functions§
- PyCFunction_
Call ⚠Deprecated - Returns a pointer to a
PyDateTime_CAPIinstance - Check if
opis aPyDateTimeAPI.DateTimeTypeor subtype. - Check if
op’s type is exactlyPyDateTimeAPI.DateTimeType. - Retrieve the fold component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 1] - Retrieve the hour component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 23] - Retrieve the microsecond component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 999999] - Retrieve the minute component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 59] - Retrieve the second component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 59] - Retrieve the tzinfo component of a
PyDateTime_DateTime. Returns a pointer to aPyObjectthat should be either NULL or an instance of adatetime.tzinfosubclass. - Retrieve the days component of a
PyDateTime_Delta. - Retrieve the seconds component of a
PyDateTime_Delta. - Retrieve the seconds component of a
PyDateTime_Delta. - Retrieve the day component of a
PyDateTime_DateorPyDateTime_DateTime. Returns a signed integer in the interval[1, 31]. - Retrieve the month component of a
PyDateTime_DateorPyDateTime_DateTime. Returns a signed integer in the range[1, 12]. - Retrieve the year component of a
PyDateTime_DateorPyDateTime_DateTime. Returns a signed integer greater than 0. - Populates the
PyDateTimeAPIobject - Retrieve the fold component of a
PyDateTime_Time. Returns a signed integer in the interval[0, 1] - Retrieve the hour component of a
PyDateTime_Time. Returns a signed integer in the interval[0, 23] - Retrieve the microsecond component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 999999] - Retrieve the minute component of a
PyDateTime_Time. Returns a signed integer in the interval[0, 59] - Retrieve the second component of a
PyDateTime_DateTime. Returns a signed integer in the interval[0, 59] - Retrieve the tzinfo component of a
PyDateTime_Time. Returns a pointer to aPyObjectthat should be either NULL or an instance of adatetime.tzinfosubclass. - Type Check macros
- Check if
op’s type is exactlyPyDateTimeAPI.DateType. - Check if
opis aPyDateTimeAPI.DetaTypeor subtype. - Check if
op’s type is exactlyPyDateTimeAPI.DeltaType. - PyErr_
Fetch ⚠Deprecated - PyErr_
Normalize ⚠Exception Deprecated - PyErr_
Restore ⚠Deprecated - PyEval_
Call ⚠Function Deprecated - PyEval_
Call ⚠Method Deprecated - PyEval_
Call ⚠Object Deprecated - PyEval_
Call ⚠Object With Keywords Deprecated - PyEval_
Init ⚠Threads Deprecated - PyEval_
Threads ⚠Initialized Deprecated - Macro, trading safety for speed
- Macro, only to be used to fill in brand new lists
- PyModule_
GetFilename ⚠Deprecated - PyOS_
After ⚠Fork Deprecated - PySys_
AddWarn ⚠Option Deprecated - PySys_
AddWarn ⚠Option Unicode Deprecated - PySys_
HasWarn ⚠Options Deprecated - PySys_
SetArgv ⚠Deprecated - PySys_
SetArgv ⚠Ex Deprecated - Check if
opis aPyDateTimeAPI.TZInfoTypeor subtype. - Check if
op’s type is exactlyPyDateTimeAPI.TZInfoType. - Check if
opis aPyDateTimeAPI.TimeTypeor subtype. - Check if
op’s type is exactlyPyDateTimeAPI.TimeType. - Macro, trading safety for speed
- Macro, only to be used to fill in brand new tuples
- Py_
SetPath ⚠Deprecated - Py_
SetProgram ⚠Name Deprecated - Py_
SetPython ⚠Home Deprecated - Get the frame evaluation function.
- Set the frame evaluation function.
Type Aliases§
- _PyC
Function Fast Deprecated - _PyC
Function Fast With Keywords Deprecated
Unions§
- Function types used to implement Python callables.
- This union is anonymous in CPython, so the name was given by PyO3 because Rust unions need a name.