pyo3/types/
mod.rs

1//! Various types defined by the Python interpreter such as `int`, `str` and `tuple`.
2
3pub use self::any::{PyAny, PyAnyMethods};
4pub use self::boolobject::{PyBool, PyBoolMethods};
5pub use self::bytearray::{PyByteArray, PyByteArrayMethods};
6pub use self::bytes::{PyBytes, PyBytesMethods};
7pub use self::capsule::{CapsuleName, PyCapsule, PyCapsuleMethods};
8pub use self::code::{PyCode, PyCodeInput, PyCodeMethods};
9pub use self::complex::{PyComplex, PyComplexMethods};
10#[allow(deprecated)]
11pub use self::datetime::{
12    timezone_utc, PyDate, PyDateTime, PyDelta, PyTime, PyTzInfo, PyTzInfoAccess,
13};
14#[cfg(not(Py_LIMITED_API))]
15pub use self::datetime::{PyDateAccess, PyDeltaAccess, PyTimeAccess};
16pub use self::dict::{IntoPyDict, PyDict, PyDictMethods};
17#[cfg(not(any(PyPy, GraalPy)))]
18pub use self::dict::{PyDictItems, PyDictKeys, PyDictValues};
19pub use self::ellipsis::PyEllipsis;
20pub use self::float::{PyFloat, PyFloatMethods};
21#[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))]
22pub use self::frame::PyFrame;
23pub use self::frozenset::{PyFrozenSet, PyFrozenSetBuilder, PyFrozenSetMethods};
24pub use self::function::PyCFunction;
25#[cfg(not(Py_LIMITED_API))]
26pub use self::function::PyFunction;
27#[cfg(Py_3_9)]
28pub use self::genericalias::PyGenericAlias;
29pub use self::iterator::PyIterator;
30#[cfg(all(not(PyPy), Py_3_10))]
31pub use self::iterator::PySendResult;
32pub use self::list::{PyList, PyListMethods};
33pub use self::mapping::{PyMapping, PyMappingMethods};
34pub use self::mappingproxy::PyMappingProxy;
35pub use self::memoryview::PyMemoryView;
36pub use self::module::{PyModule, PyModuleMethods};
37#[cfg(all(not(Py_LIMITED_API), Py_3_13))]
38pub use self::mutex::{PyMutex, PyMutexGuard};
39pub use self::none::PyNone;
40pub use self::notimplemented::PyNotImplemented;
41pub use self::num::PyInt;
42pub use self::pysuper::PySuper;
43pub use self::range::{PyRange, PyRangeMethods};
44pub use self::sequence::{PySequence, PySequenceMethods};
45pub use self::set::{PySet, PySetMethods};
46pub use self::slice::{PySlice, PySliceIndices, PySliceMethods};
47#[cfg(not(Py_LIMITED_API))]
48pub use self::string::PyStringData;
49pub use self::string::{PyString, PyStringMethods};
50pub use self::traceback::{PyTraceback, PyTracebackMethods};
51pub use self::tuple::{PyTuple, PyTupleMethods};
52pub use self::typeobject::{PyType, PyTypeMethods};
53pub use self::weakref::{PyWeakref, PyWeakrefMethods, PyWeakrefProxy, PyWeakrefReference};
54
55/// Iteration over Python collections.
56///
57/// When working with a Python collection, one approach is to convert it to a Rust collection such
58/// as `Vec` or `HashMap`. However this is a relatively expensive operation. If you just want to
59/// visit all their items, consider iterating over the collections directly:
60///
61/// # Examples
62///
63/// ```rust
64/// use pyo3::prelude::*;
65/// use pyo3::types::PyDict;
66/// use pyo3::ffi::c_str;
67///
68/// # pub fn main() -> PyResult<()> {
69/// Python::attach(|py| {
70///     let dict = py.eval(c"{'a':'b', 'c':'d'}", None, None)?.cast_into::<PyDict>()?;
71///
72///     for (key, value) in &dict {
73///         println!("key: {}, value: {}", key, value);
74///     }
75///
76///     Ok(())
77/// })
78/// # }
79///  ```
80///
81/// If PyO3 detects that the collection is mutated during iteration, it will panic.
82///
83/// These iterators use Python's C-API directly. However in certain cases, like when compiling for
84/// the Limited API and PyPy, the underlying structures are opaque and that may not be possible.
85/// In these cases the iterators are implemented by forwarding to [`PyIterator`].
86pub mod iter {
87    pub use super::dict::BoundDictIterator;
88    pub use super::frozenset::BoundFrozenSetIterator;
89    pub use super::list::BoundListIterator;
90    pub use super::set::BoundSetIterator;
91    pub use super::tuple::{BorrowedTupleIterator, BoundTupleIterator};
92}
93
94/// Python objects that have a base type.
95///
96/// This marks types that can be upcast into a [`PyAny`] and used in its place.
97/// This essentially includes every Python object except [`PyAny`] itself.
98///
99/// This is used to provide the [`Deref<Target = Bound<'_, PyAny>>`](std::ops::Deref)
100/// implementations for [`Bound<'_, T>`](crate::Bound).
101///
102/// Users should not need to implement this trait directly. It's implementation
103/// is provided by the [`#[pyclass]`](macro@crate::pyclass) attribute.
104///
105/// ## Note
106/// This is needed because the compiler currently tries to figure out all the
107/// types in a deref-chain before starting to look for applicable method calls.
108/// So we need to prevent [`Bound<'_, PyAny`](crate::Bound) dereferencing to
109/// itself in order to avoid running into the recursion limit. This trait is
110/// used to exclude this from our blanket implementation. See [this Rust
111/// issue][1] for more details. If the compiler limitation gets resolved, this
112/// trait will be removed.
113///
114/// [1]: https://github.com/rust-lang/rust/issues/19509
115pub trait DerefToPyAny {
116    // Empty.
117}
118
119// Implementations core to all native types except for PyAny (because they don't
120// make sense on PyAny / have different implementations).
121#[doc(hidden)]
122#[macro_export]
123macro_rules! pyobject_native_type_named (
124    ($name:ty $(;$generics:ident)*) => {
125        impl $crate::types::DerefToPyAny for $name {}
126    };
127);
128
129/// Helper for defining the `$typeobject` argument for other macros in this module.
130///
131/// # Safety
132///
133/// - `$typeobject` must be a known `static mut PyTypeObject`
134#[doc(hidden)]
135#[macro_export]
136macro_rules! pyobject_native_static_type_object(
137    ($typeobject:expr) => {
138        |_py| ::std::ptr::addr_of_mut!($typeobject)
139    };
140);
141
142/// Adds a TYPE_HINT constant if the `experimental-inspect`  feature is enabled.
143#[cfg(not(feature = "experimental-inspect"))]
144#[doc(hidden)]
145#[macro_export]
146macro_rules! pyobject_type_info_type_hint(
147    ($module:expr, $name:expr) => {};
148);
149
150#[cfg(feature = "experimental-inspect")]
151#[doc(hidden)]
152#[macro_export]
153macro_rules! pyobject_type_info_type_hint(
154    ($module:expr, $name:expr) => {
155        const TYPE_HINT: $crate::inspect::TypeHint = $crate::inspect::TypeHint::module_attr($module, $name);
156    };
157);
158
159/// Implements the `PyTypeInfo` trait for a native Python type.
160///
161/// # Safety
162///
163/// - `$typeobject` must be a function that produces a valid `*mut PyTypeObject`
164/// - `$checkfunction` must be a function that accepts arbitrary `*mut PyObject` and returns true /
165///   false according to whether the object is an instance of the type from `$typeobject`
166#[doc(hidden)]
167#[macro_export]
168macro_rules! pyobject_native_type_info(
169    ($name:ty, $typeobject:expr, $type_hint_module:expr, $type_hint_name:expr, $module:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
170        // SAFETY: macro caller has upheld the safety contracts
171        unsafe impl<$($generics,)*> $crate::type_object::PyTypeInfo for $name {
172            const NAME: &'static str = stringify!($name);
173            const MODULE: ::std::option::Option<&'static str> = $module;
174            $crate::pyobject_type_info_type_hint!($type_hint_module, $type_hint_name);
175
176            #[inline]
177            #[allow(clippy::redundant_closure_call)]
178            fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject {
179                $typeobject(py)
180            }
181
182            $(
183                #[inline]
184                fn is_type_of(obj: &$crate::Bound<'_, $crate::PyAny>) -> bool {
185                    #[allow(unused_unsafe, reason = "not all `$checkfunction` are unsafe fn")]
186                    // SAFETY: `$checkfunction` is being called with a valid `PyObject` pointer
187                    unsafe { $checkfunction(obj.as_ptr()) > 0 }
188                }
189            )?
190        }
191
192        impl $name {
193            #[doc(hidden)]
194            pub const _PYO3_DEF: $crate::impl_::pymodule::AddTypeToModule<Self> = $crate::impl_::pymodule::AddTypeToModule::new();
195
196            #[allow(dead_code)]
197            #[doc(hidden)]
198            pub const _PYO3_INTROSPECTION_ID: &'static str = concat!(stringify!($module), stringify!($name));
199        }
200    };
201);
202
203/// Declares all of the boilerplate for Python types.
204#[doc(hidden)]
205#[macro_export]
206macro_rules! pyobject_native_type_core {
207    ($name:ty, $typeobject:expr, $type_hint_module:expr, $type_hint_name:expr, #module=$module:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
208        $crate::pyobject_native_type_named!($name $(;$generics)*);
209        $crate::pyobject_native_type_info!($name, $typeobject, $type_hint_module, $type_hint_name, $module $(, #checkfunction=$checkfunction)? $(;$generics)*);
210    };
211    ($name:ty, $typeobject:expr, $type_hint_module:expr, $type_hint_name:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
212        $crate::pyobject_native_type_core!($name, $typeobject, $type_hint_module, $type_hint_name, #module=::std::option::Option::Some("builtins") $(, #checkfunction=$checkfunction)? $(;$generics)*);
213    };
214}
215
216#[doc(hidden)]
217#[macro_export]
218macro_rules! pyobject_subclassable_native_type {
219    ($name:ty, $layout:path $(;$generics:ident)*) => {
220        #[cfg(not(Py_LIMITED_API))]
221        impl<$($generics,)*> $crate::impl_::pyclass::PyClassBaseType for $name {
222            type LayoutAsBase = $crate::impl_::pycell::PyClassObjectBase<$layout>;
223            type BaseNativeType = $name;
224            type Initializer = $crate::impl_::pyclass_init::PyNativeTypeInitializer<Self>;
225            type PyClassMutability = $crate::pycell::impl_::ImmutableClass;
226        }
227    }
228}
229
230#[doc(hidden)]
231#[macro_export]
232macro_rules! pyobject_native_type_sized {
233    ($name:ty, $layout:path $(;$generics:ident)*) => {
234        unsafe impl $crate::type_object::PyLayout<$name> for $layout {}
235        impl $crate::type_object::PySizedLayout<$name> for $layout {}
236    };
237}
238
239/// Declares all of the boilerplate for Python types which can be inherited from (because the exact
240/// Python layout is known).
241#[doc(hidden)]
242#[macro_export]
243macro_rules! pyobject_native_type {
244    ($name:ty, $layout:path, $typeobject:expr, $type_hint_module:expr, $type_hint_name:expr $(, #module=$module:expr)? $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
245        $crate::pyobject_native_type_core!($name, $typeobject, $type_hint_module, $type_hint_name $(, #module=$module)? $(, #checkfunction=$checkfunction)? $(;$generics)*);
246        // To prevent inheriting native types with ABI3
247        #[cfg(not(Py_LIMITED_API))]
248        $crate::pyobject_native_type_sized!($name, $layout $(;$generics)*);
249    };
250}
251
252pub(crate) mod any;
253pub(crate) mod boolobject;
254pub(crate) mod bytearray;
255pub(crate) mod bytes;
256pub(crate) mod capsule;
257mod code;
258pub(crate) mod complex;
259pub(crate) mod datetime;
260pub(crate) mod dict;
261mod ellipsis;
262pub(crate) mod float;
263#[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))]
264mod frame;
265pub(crate) mod frozenset;
266mod function;
267#[cfg(Py_3_9)]
268pub(crate) mod genericalias;
269pub(crate) mod iterator;
270pub(crate) mod list;
271pub(crate) mod mapping;
272pub(crate) mod mappingproxy;
273mod memoryview;
274pub(crate) mod module;
275#[cfg(all(not(Py_LIMITED_API), Py_3_13))]
276mod mutex;
277mod none;
278mod notimplemented;
279mod num;
280mod pysuper;
281pub(crate) mod range;
282pub(crate) mod sequence;
283pub(crate) mod set;
284pub(crate) mod slice;
285pub(crate) mod string;
286pub(crate) mod traceback;
287pub(crate) mod tuple;
288pub(crate) mod typeobject;
289pub(crate) mod weakref;