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
: Marks code that is only enabled when compiling for a given minimum Python version.Py_LIMITED_API
: Marks code enabled when theabi3
feature flag is enabled.PyPy
- Marks code enabled when compiling for PyPy.
§Minimum supported Rust and Python versions
PyO3 supports the following software versions:
- Python 3.7 and up (CPython and PyPy)
- Rust 1.63 and up
§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.22.2"
features = ["extension-module"]
src/lib.rs
use std::os::raw::c_char;
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_mut_ptr().cast() },
m_slots: std::ptr::null_mut(),
m_traverse: None,
m_clear: None,
m_free: None,
};
static mut METHODS: [PyMethodDef; 2] = [
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 {
PyModule_Create(ptr::addr_of_mut!(MODULE_DEF))
}
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 arg1 = *args;
if PyLong_Check(arg1) == 0 {
PyErr_SetString(
PyExc_TypeError,
c_str!("sum_as_string() expected an int for positional argument 1").as_ptr(),
);
return std::ptr::null_mut();
}
let arg1 = PyLong_AsLong(arg1);
if !PyErr_Occurred().is_null() {
return ptr::null_mut();
}
let arg2 = *args.add(1);
if PyLong_Check(arg2) == 0 {
PyErr_SetString(
PyExc_TypeError,
c_str!("sum_as_string() expected an int for positional argument 2").as_ptr(),
);
return std::ptr::null_mut();
}
let arg2 = PyLong_AsLong(arg2);
if !PyErr_Occurred().is_null() {
return ptr::null_mut();
}
match arg1.checked_add(arg2) {
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 maturin
Now 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.
§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-dev
While 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§
- 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.datetime
without atzinfo
member. - Structure representing a
datetime.time
without atzinfo
member.
Enums§
Constants§
- Maximum number of dimensions
- PyUnicode_
WCHAR_ KIND Deprecated - 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_CAPI
instance - Check if
op
is aPyDateTimeAPI.DateTimeType
or 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 aPyObject
that should be either NULL or an instance of adatetime.tzinfo
subclass. - 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_Date
orPyDateTime_DateTime
. Returns a signed integer in the interval[1, 31]
. - Retrieve the month component of a
PyDateTime_Date
orPyDateTime_DateTime
. Returns a signed integer in the range[1, 12]
. - Retrieve the year component of a
PyDateTime_Date
orPyDateTime_DateTime
. Returns a signed integer greater than 0. - Populates the
PyDateTimeAPI
object - 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 aPyObject
that should be either NULL or an instance of adatetime.tzinfo
subclass. - Type Check macros
- Check if
op
’s type is exactlyPyDateTimeAPI.DateType
. - Check if
op
is aPyDateTimeAPI.DetaType
or subtype. - Check if
op
’s type is exactlyPyDateTimeAPI.DeltaType
. - PyEval_
Call ⚠Function Deprecated - PyEval_
Call ⚠Method Deprecated - PyEval_
Call ⚠Object Deprecated - PyEval_
Call ⚠Object With Keywords Deprecated - Macro, trading safety for speed
- Macro, only to be used to fill in brand new lists
- PyModule_
GetFilename ⚠Deprecated - PyOS_
After ⚠Fork Deprecated - Check if
op
is aPyDateTimeAPI.TZInfoType
or subtype. - Check if
op
’s type is exactlyPyDateTimeAPI.TZInfoType
. - Check if
op
is aPyDateTimeAPI.TimeType
or 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
- PyUnicode_
AsUnicode ⚠Deprecated - PyUnicode_
AsUnicode ⚠AndSize Deprecated - PyUnicode_
From ⚠Unicode Deprecated - PyUnicode_
GetSize ⚠Deprecated - PyUnicode_
Intern ⚠Immortal Deprecated - Get the frame evaluation function.
- Set the frame evaluation function.
Type Aliases§
Unions§
- Function types used to implement Python callables.