When writing functions callable from Python (such as a
#[pyfunction] or in a
#[pymethods] block), the trait
FromPyObject is required for function arguments, and
IntoPy<PyObject> is required for function return values.
Consult the tables in the following section to find the Rust types provided by PyO3 which implement these traits.
When accepting a function argument, it is possible to either use Rust library types or PyO3's Python-native types. (See the next section for discussion on when to use each.)
The table below contains the Python type and the corresponding function argument types that will accept them:
|Any integer type (|
There are also a few special types related to the GIL and Rust-defined
#[pyclass]es which may come in useful:
|A GIL token, used to pass to PyO3 constructors to prove ownership of the GIL|
|A Python object isolated from the GIL lifetime. This can be sent to other threads.|
|An alias for |
For more detail on accepting
#[pyclass] values as function arguments, see the section of this guide on Python Classes.
Using Rust library types as function arguments will incur a conversion cost compared to using the Python-native types. Using the Python-native types is almost zero-cost (they just require a type check similar to the Python builtin function
However, once that conversion cost has been paid, the Rust standard library types offer a number of benefits:
- You can write functionality in native-speed Rust code (free of Python's runtime costs).
- You get better interoperability with the rest of the Rust ecosystem.
- You can use
Python::allow_threadsto release the Python GIL and let other Python threads make progress while your Rust code is executing.
- You also benefit from stricter type checking. For example you can specify
Vec<i32>, which will only accept a Python
listcontaining integers. The Python-native equivalent,
&PyList, would accept a Python
listcontaining Python objects of any type.
For most PyO3 usage the conversion cost is worth paying to get these benefits. As always, if you're not sure it's worth it in your case, benchmark it!
When returning values from functions callable from Python, Python-native types (
&PyDict etc.) can be used with zero cost.
Because these types are references, in some situations the Rust compiler may ask for lifetime annotations. If this is the case, you should use
Py<PyDict> etc. instead - which are also zero-cost. For all of these Python-native types
Py<T> can be created from
T with an
If your function is fallible, it should return
Result<T, E> where
From<E> for PyErr. This will raise a
Python exception if the
Err variant is returned.
Finally, the following Rust types are also able to convert to Python as return values:
|Rust type||Resulting Python Type|
|Any integer type (|
num-complex optional feature.
hashbrown optional feature.
indexmap optional feature.