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::{PyCapsule, PyCapsuleMethods};
8#[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))]
9pub use self::code::PyCode;
10pub use self::complex::{PyComplex, PyComplexMethods};
11#[cfg(not(Py_LIMITED_API))]
12#[allow(deprecated)]
13pub use self::datetime::{
14    timezone_utc, timezone_utc_bound, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess,
15    PyTime, PyTimeAccess, PyTzInfo, PyTzInfoAccess,
16};
17pub use self::dict::{IntoPyDict, PyDict, PyDictMethods};
18#[cfg(not(any(PyPy, GraalPy)))]
19pub use self::dict::{PyDictItems, PyDictKeys, PyDictValues};
20pub use self::ellipsis::PyEllipsis;
21pub use self::float::{PyFloat, PyFloatMethods};
22#[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))]
23pub use self::frame::PyFrame;
24pub use self::frozenset::{PyFrozenSet, PyFrozenSetBuilder, PyFrozenSetMethods};
25pub use self::function::PyCFunction;
26#[cfg(all(not(Py_LIMITED_API), not(all(PyPy, not(Py_3_8)))))]
27pub use self::function::PyFunction;
28pub use self::iterator::PyIterator;
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};
34pub use self::none::PyNone;
35pub use self::notimplemented::PyNotImplemented;
36#[allow(deprecated)]
37pub use self::num::{PyInt, PyLong};
38#[cfg(not(any(PyPy, GraalPy)))]
39pub use self::pysuper::PySuper;
40pub use self::sequence::{PySequence, PySequenceMethods};
41pub use self::set::{PySet, PySetMethods};
42pub use self::slice::{PySlice, PySliceIndices, PySliceMethods};
43#[cfg(not(Py_LIMITED_API))]
44pub use self::string::PyStringData;
45#[allow(deprecated)]
46pub use self::string::{PyString, PyStringMethods, PyUnicode};
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/// use pyo3::ffi::c_str;
64///
65/// # pub fn main() -> PyResult<()> {
66/// Python::with_gil(|py| {
67///     let dict = py.eval(c_str!("{'a':'b', 'c':'d'}"), None, None)?.downcast_into::<PyDict>()?;
68///
69///     for (key, value) in &dict {
70///         println!("key: {}, value: {}", key, value);
71///     }
72///
73///     Ok(())
74/// })
75/// # }
76///  ```
77///
78/// If PyO3 detects that the collection is mutated during iteration, it will panic.
79///
80/// These iterators use Python's C-API directly. However in certain cases, like when compiling for
81/// the Limited API and PyPy, the underlying structures are opaque and that may not be possible.
82/// In these cases the iterators are implemented by forwarding to [`PyIterator`].
83pub mod iter {
84    pub use super::dict::BoundDictIterator;
85    pub use super::frozenset::BoundFrozenSetIterator;
86    pub use super::list::BoundListIterator;
87    pub use super::set::BoundSetIterator;
88    pub use super::tuple::{BorrowedTupleIterator, BoundTupleIterator};
89}
90
91/// Python objects that have a base type.
92///
93/// This marks types that can be upcast into a [`PyAny`] and used in its place.
94/// This essentially includes every Python object except [`PyAny`] itself.
95///
96/// This is used to provide the [`Deref<Target = Bound<'_, PyAny>>`](std::ops::Deref)
97/// implementations for [`Bound<'_, T>`](crate::Bound).
98///
99/// Users should not need to implement this trait directly. It's implementation
100/// is provided by the [`#[pyclass]`](macro@crate::pyclass) attribute.
101///
102/// ## Note
103/// This is needed because the compiler currently tries to figure out all the
104/// types in a deref-chain before starting to look for applicable method calls.
105/// So we need to prevent [`Bound<'_, PyAny`](crate::Bound) dereferencing to
106/// itself in order to avoid running into the recursion limit. This trait is
107/// used to exclude this from our blanket implementation. See [this Rust
108/// issue][1] for more details. If the compiler limitation gets resolved, this
109/// trait will be removed.
110///
111/// [1]: https://github.com/rust-lang/rust/issues/19509
112pub trait DerefToPyAny {
113    // Empty.
114}
115
116// Implementations core to all native types except for PyAny (because they don't
117// make sense on PyAny / have different implementations).
118#[doc(hidden)]
119#[macro_export]
120macro_rules! pyobject_native_type_named (
121    ($name:ty $(;$generics:ident)*) => {
122        impl<$($generics,)*> ::std::convert::AsRef<$crate::PyAny> for $name {
123            #[inline]
124            fn as_ref(&self) -> &$crate::PyAny {
125                &self.0
126            }
127        }
128
129        impl<$($generics,)*> ::std::ops::Deref for $name {
130            type Target = $crate::PyAny;
131
132            #[inline]
133            fn deref(&self) -> &$crate::PyAny {
134                &self.0
135            }
136        }
137
138        impl $crate::types::DerefToPyAny for $name {}
139    };
140);
141
142#[doc(hidden)]
143#[macro_export]
144macro_rules! pyobject_native_static_type_object(
145    ($typeobject:expr) => {
146        |_py| {
147            #[allow(unused_unsafe)] // https://github.com/rust-lang/rust/pull/125834
148            unsafe { ::std::ptr::addr_of_mut!($typeobject) }
149        }
150    };
151);
152
153#[doc(hidden)]
154#[macro_export]
155macro_rules! pyobject_native_type_info(
156    ($name:ty, $typeobject:expr, $module:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
157        unsafe impl<$($generics,)*> $crate::type_object::PyTypeInfo for $name {
158            const NAME: &'static str = stringify!($name);
159            const MODULE: ::std::option::Option<&'static str> = $module;
160
161            #[inline]
162            #[allow(clippy::redundant_closure_call)]
163            fn type_object_raw(py: $crate::Python<'_>) -> *mut $crate::ffi::PyTypeObject {
164                $typeobject(py)
165            }
166
167            $(
168                #[inline]
169                fn is_type_of_bound(obj: &$crate::Bound<'_, $crate::PyAny>) -> bool {
170                    #[allow(unused_unsafe)]
171                    unsafe { $checkfunction(obj.as_ptr()) > 0 }
172                }
173            )?
174        }
175
176        impl $name {
177            #[doc(hidden)]
178            pub const _PYO3_DEF: $crate::impl_::pymodule::AddTypeToModule<Self> = $crate::impl_::pymodule::AddTypeToModule::new();
179        }
180    };
181);
182
183/// Declares all of the boilerplate for Python types.
184#[doc(hidden)]
185#[macro_export]
186macro_rules! pyobject_native_type_core {
187    ($name:ty, $typeobject:expr, #module=$module:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
188        $crate::pyobject_native_type_named!($name $(;$generics)*);
189        $crate::pyobject_native_type_info!($name, $typeobject, $module $(, #checkfunction=$checkfunction)? $(;$generics)*);
190    };
191    ($name:ty, $typeobject:expr $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
192        $crate::pyobject_native_type_core!($name, $typeobject, #module=::std::option::Option::Some("builtins") $(, #checkfunction=$checkfunction)? $(;$generics)*);
193    };
194}
195
196#[doc(hidden)]
197#[macro_export]
198macro_rules! pyobject_subclassable_native_type {
199    ($name:ty, $layout:path $(;$generics:ident)*) => {
200        #[cfg(not(Py_LIMITED_API))]
201        impl<$($generics,)*> $crate::impl_::pyclass::PyClassBaseType for $name {
202            type LayoutAsBase = $crate::impl_::pycell::PyClassObjectBase<$layout>;
203            type BaseNativeType = $name;
204            type Initializer = $crate::impl_::pyclass_init::PyNativeTypeInitializer<Self>;
205            type PyClassMutability = $crate::pycell::impl_::ImmutableClass;
206        }
207    }
208}
209
210#[doc(hidden)]
211#[macro_export]
212macro_rules! pyobject_native_type_sized {
213    ($name:ty, $layout:path $(;$generics:ident)*) => {
214        unsafe impl $crate::type_object::PyLayout<$name> for $layout {}
215        impl $crate::type_object::PySizedLayout<$name> for $layout {}
216    };
217}
218
219/// Declares all of the boilerplate for Python types which can be inherited from (because the exact
220/// Python layout is known).
221#[doc(hidden)]
222#[macro_export]
223macro_rules! pyobject_native_type {
224    ($name:ty, $layout:path, $typeobject:expr $(, #module=$module:expr)? $(, #checkfunction=$checkfunction:path)? $(;$generics:ident)*) => {
225        $crate::pyobject_native_type_core!($name, $typeobject $(, #module=$module)? $(, #checkfunction=$checkfunction)? $(;$generics)*);
226        // To prevent inheriting native types with ABI3
227        #[cfg(not(Py_LIMITED_API))]
228        $crate::pyobject_native_type_sized!($name, $layout $(;$generics)*);
229    };
230}
231
232pub(crate) mod any;
233pub(crate) mod boolobject;
234pub(crate) mod bytearray;
235pub(crate) mod bytes;
236pub(crate) mod capsule;
237#[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))]
238mod code;
239pub(crate) mod complex;
240#[cfg(not(Py_LIMITED_API))]
241pub(crate) mod datetime;
242pub(crate) mod dict;
243mod ellipsis;
244pub(crate) mod float;
245#[cfg(all(not(Py_LIMITED_API), not(PyPy), not(GraalPy)))]
246mod frame;
247pub(crate) mod frozenset;
248mod function;
249pub(crate) mod iterator;
250pub(crate) mod list;
251pub(crate) mod mapping;
252pub(crate) mod mappingproxy;
253mod memoryview;
254pub(crate) mod module;
255mod none;
256mod notimplemented;
257mod num;
258#[cfg(not(any(PyPy, GraalPy)))]
259mod pysuper;
260pub(crate) mod sequence;
261pub(crate) mod set;
262pub(crate) mod slice;
263pub(crate) mod string;
264pub(crate) mod traceback;
265pub(crate) mod tuple;
266pub(crate) mod typeobject;
267pub(crate) mod weakref;