Skip to main content

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