pyo3/
type_object.rs

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