pyo3/type_object.rs
1//! Python type object information
2
3use crate::ffi_ptr_ext::FfiPtrExt;
4use crate::types::any::PyAnyMethods;
5use crate::types::{PyAny, PyType};
6use crate::{ffi, Bound, Python};
7use std::ptr;
8
9/// `T: PyLayout<U>` represents that `T` is a concrete representation of `U` in the Python heap.
10/// E.g., `PyClassObject` is a concrete representation of all `pyclass`es, and `ffi::PyObject`
11/// is of `PyAny`.
12///
13/// This trait is intended to be used internally.
14///
15/// # Safety
16///
17/// This trait must only be implemented for types which represent valid layouts of Python objects.
18pub unsafe trait PyLayout<T> {}
19
20/// `T: PySizedLayout<U>` represents that `T` is not a instance of
21/// [`PyVarObject`](https://docs.python.org/3/c-api/structures.html#c.PyVarObject).
22///
23/// In addition, that `T` is a concrete representation of `U`.
24pub trait PySizedLayout<T>: PyLayout<T> + Sized {}
25
26/// Python type information.
27/// All Python native types (e.g., `PyDict`) and `#[pyclass]` structs implement this trait.
28///
29/// This trait is marked unsafe because:
30/// - specifying the incorrect layout can lead to memory errors
31/// - the return value of type_object must always point to the same PyTypeObject instance
32///
33/// It is safely implemented by the `pyclass` macro.
34///
35/// # Safety
36///
37/// Implementations must provide an implementation for `type_object_raw` which infallibly produces a
38/// non-null pointer to the corresponding Python type object.
39pub unsafe trait PyTypeInfo: Sized {
40 /// Class name.
41 const NAME: &'static str;
42
43 /// Module name, if any.
44 const MODULE: Option<&'static str>;
45
46 /// Provides the full python type paths.
47 #[cfg(feature = "experimental-inspect")]
48 const PYTHON_TYPE: &'static str = "typing.Any";
49
50 /// Returns the PyTypeObject instance for this type.
51 fn type_object_raw(py: Python<'_>) -> *mut ffi::PyTypeObject;
52
53 /// Returns the safe abstraction over the type object.
54 #[inline]
55 fn type_object(py: Python<'_>) -> Bound<'_, PyType> {
56 // Making the borrowed object `Bound` is necessary for soundness reasons. It's an extreme
57 // edge case, but arbitrary Python code _could_ change the __class__ of an object and cause
58 // the type object to be freed.
59 //
60 // By making `Bound` we assume ownership which is then safe against races.
61 unsafe {
62 Self::type_object_raw(py)
63 .cast::<ffi::PyObject>()
64 .assume_borrowed_unchecked(py)
65 .to_owned()
66 .downcast_into_unchecked()
67 }
68 }
69
70 /// Checks if `object` is an instance of this type or a subclass of this type.
71 #[inline]
72 fn is_type_of(object: &Bound<'_, PyAny>) -> bool {
73 unsafe { ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object_raw(object.py())) != 0 }
74 }
75
76 /// Checks if `object` is an instance of this type.
77 #[inline]
78 fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool {
79 unsafe {
80 ptr::eq(
81 ffi::Py_TYPE(object.as_ptr()),
82 Self::type_object_raw(object.py()),
83 )
84 }
85 }
86}
87
88/// Implemented by types which can be used as a concrete Python type inside `Py<T>` smart pointers.
89pub trait PyTypeCheck {
90 /// Name of self. This is used in error messages, for example.
91 const NAME: &'static str;
92
93 /// Provides the full python type of the allowed values.
94 #[cfg(feature = "experimental-inspect")]
95 const PYTHON_TYPE: &'static str;
96
97 /// Checks if `object` is an instance of `Self`, which may include a subtype.
98 ///
99 /// This should be equivalent to the Python expression `isinstance(object, Self)`.
100 fn type_check(object: &Bound<'_, PyAny>) -> bool;
101}
102
103impl<T> PyTypeCheck for T
104where
105 T: PyTypeInfo,
106{
107 const NAME: &'static str = <T as PyTypeInfo>::NAME;
108
109 #[cfg(feature = "experimental-inspect")]
110 const PYTHON_TYPE: &'static str = <T as PyTypeInfo>::PYTHON_TYPE;
111
112 #[inline]
113 fn type_check(object: &Bound<'_, PyAny>) -> bool {
114 T::is_type_of(object)
115 }
116}