Skip to main content

pyo3/types/
mod.rs

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