1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use crate::err::{self, PyResult};
use crate::instance::Borrowed;
#[cfg(not(Py_3_13))]
use crate::pybacked::PyBackedStr;
use crate::types::any::PyAnyMethods;
use crate::types::PyTuple;
use crate::{ffi, Bound, PyAny, PyTypeInfo, Python};

use super::PyString;

/// Represents a reference to a Python `type` object.
///
/// Values of this type are accessed via PyO3's smart pointers, e.g. as
/// [`Py<PyType>`][crate::Py] or [`Bound<'py, PyType>`][Bound].
///
/// For APIs available on `type` objects, see the [`PyTypeMethods`] trait which is implemented for
/// [`Bound<'py, PyType>`][Bound].
#[repr(transparent)]
pub struct PyType(PyAny);

pyobject_native_type_core!(PyType, pyobject_native_static_type_object!(ffi::PyType_Type), #checkfunction=ffi::PyType_Check);

impl PyType {
    /// Creates a new type object.
    #[inline]
    pub fn new_bound<T: PyTypeInfo>(py: Python<'_>) -> Bound<'_, PyType> {
        T::type_object_bound(py)
    }

    /// Converts the given FFI pointer into `Bound<PyType>`, to use in safe code.
    ///
    /// The function creates a new reference from the given pointer, and returns
    /// it as a `Bound<PyType>`.
    ///
    /// # Safety
    /// - The pointer must be a valid non-null reference to a `PyTypeObject`
    #[inline]
    pub unsafe fn from_borrowed_type_ptr(
        py: Python<'_>,
        p: *mut ffi::PyTypeObject,
    ) -> Bound<'_, PyType> {
        Borrowed::from_ptr_unchecked(py, p.cast())
            .downcast_unchecked()
            .to_owned()
    }
}

/// Implementation of functionality for [`PyType`].
///
/// These methods are defined for the `Bound<'py, PyType>` smart pointer, so to use method call
/// syntax these methods are separated into a trait, because stable Rust does not yet support
/// `arbitrary_self_types`.
#[doc(alias = "PyType")]
pub trait PyTypeMethods<'py>: crate::sealed::Sealed {
    /// Retrieves the underlying FFI pointer associated with this Python object.
    fn as_type_ptr(&self) -> *mut ffi::PyTypeObject;

    /// Gets the name of the `PyType`. Equivalent to `self.__name__` in Python.
    fn name(&self) -> PyResult<Bound<'py, PyString>>;

    /// Gets the [qualified name](https://docs.python.org/3/glossary.html#term-qualified-name) of the `PyType`.
    /// Equivalent to `self.__qualname__` in Python.
    fn qualname(&self) -> PyResult<Bound<'py, PyString>>;

    /// Gets the name of the module defining the `PyType`.
    fn module(&self) -> PyResult<Bound<'py, PyString>>;

    /// Gets the [fully qualified name](https://peps.python.org/pep-0737/#add-pytype-getfullyqualifiedname-function) of the `PyType`.
    fn fully_qualified_name(&self) -> PyResult<Bound<'py, PyString>>;

    /// Checks whether `self` is a subclass of `other`.
    ///
    /// Equivalent to the Python expression `issubclass(self, other)`.
    fn is_subclass(&self, other: &Bound<'_, PyAny>) -> PyResult<bool>;

    /// Checks whether `self` is a subclass of type `T`.
    ///
    /// Equivalent to the Python expression `issubclass(self, T)`, if the type
    /// `T` is known at compile time.
    fn is_subclass_of<T>(&self) -> PyResult<bool>
    where
        T: PyTypeInfo;

    /// Return the method resolution order for this type.
    ///
    /// Equivalent to the Python expression `self.__mro__`.
    fn mro(&self) -> Bound<'py, PyTuple>;

    /// Return Python bases
    ///
    /// Equivalent to the Python expression `self.__bases__`.
    fn bases(&self) -> Bound<'py, PyTuple>;
}

impl<'py> PyTypeMethods<'py> for Bound<'py, PyType> {
    /// Retrieves the underlying FFI pointer associated with this Python object.
    #[inline]
    fn as_type_ptr(&self) -> *mut ffi::PyTypeObject {
        self.as_ptr() as *mut ffi::PyTypeObject
    }

    /// Gets the name of the `PyType`.
    fn name(&self) -> PyResult<Bound<'py, PyString>> {
        #[cfg(not(Py_3_11))]
        let name = self
            .getattr(intern!(self.py(), "__name__"))?
            .downcast_into()?;

        #[cfg(Py_3_11)]
        let name = unsafe {
            use crate::ffi_ptr_ext::FfiPtrExt;
            ffi::PyType_GetName(self.as_type_ptr())
                .assume_owned_or_err(self.py())?
                // SAFETY: setting `__name__` from Python is required to be a `str`
                .downcast_into_unchecked()
        };

        Ok(name)
    }

    /// Gets the [qualified name](https://docs.python.org/3/glossary.html#term-qualified-name) of the `PyType`.
    fn qualname(&self) -> PyResult<Bound<'py, PyString>> {
        #[cfg(not(Py_3_11))]
        let name = self
            .getattr(intern!(self.py(), "__qualname__"))?
            .downcast_into()?;

        #[cfg(Py_3_11)]
        let name = unsafe {
            use crate::ffi_ptr_ext::FfiPtrExt;
            ffi::PyType_GetQualName(self.as_type_ptr())
                .assume_owned_or_err(self.py())?
                // SAFETY: setting `__qualname__` from Python is required to be a `str`
                .downcast_into_unchecked()
        };

        Ok(name)
    }

    /// Gets the name of the module defining the `PyType`.
    fn module(&self) -> PyResult<Bound<'py, PyString>> {
        #[cfg(not(Py_3_13))]
        let name = self.getattr(intern!(self.py(), "__module__"))?;

        #[cfg(Py_3_13)]
        let name = unsafe {
            use crate::ffi_ptr_ext::FfiPtrExt;
            ffi::PyType_GetModuleName(self.as_type_ptr()).assume_owned_or_err(self.py())?
        };

        // `__module__` is never guaranteed to be a `str`
        name.downcast_into().map_err(Into::into)
    }

    /// Gets the [fully qualified name](https://docs.python.org/3/glossary.html#term-qualified-name) of the `PyType`.
    fn fully_qualified_name(&self) -> PyResult<Bound<'py, PyString>> {
        #[cfg(not(Py_3_13))]
        let name = {
            let module = self.getattr(intern!(self.py(), "__module__"))?;
            let qualname = self.getattr(intern!(self.py(), "__qualname__"))?;

            let module_str = module.extract::<PyBackedStr>()?;
            if module_str == "builtins" || module_str == "__main__" {
                qualname.downcast_into()?
            } else {
                PyString::new_bound(self.py(), &format!("{}.{}", module, qualname))
            }
        };

        #[cfg(Py_3_13)]
        let name = unsafe {
            use crate::ffi_ptr_ext::FfiPtrExt;
            ffi::PyType_GetFullyQualifiedName(self.as_type_ptr())
                .assume_owned_or_err(self.py())?
                .downcast_into_unchecked()
        };

        Ok(name)
    }

    /// Checks whether `self` is a subclass of `other`.
    ///
    /// Equivalent to the Python expression `issubclass(self, other)`.
    fn is_subclass(&self, other: &Bound<'_, PyAny>) -> PyResult<bool> {
        let result = unsafe { ffi::PyObject_IsSubclass(self.as_ptr(), other.as_ptr()) };
        err::error_on_minusone(self.py(), result)?;
        Ok(result == 1)
    }

    /// Checks whether `self` is a subclass of type `T`.
    ///
    /// Equivalent to the Python expression `issubclass(self, T)`, if the type
    /// `T` is known at compile time.
    fn is_subclass_of<T>(&self) -> PyResult<bool>
    where
        T: PyTypeInfo,
    {
        self.is_subclass(&T::type_object_bound(self.py()))
    }

    fn mro(&self) -> Bound<'py, PyTuple> {
        #[cfg(any(Py_LIMITED_API, PyPy))]
        let mro = self
            .getattr(intern!(self.py(), "__mro__"))
            .expect("Cannot get `__mro__` from object.")
            .extract()
            .expect("Unexpected type in `__mro__` attribute.");

        #[cfg(not(any(Py_LIMITED_API, PyPy)))]
        let mro = unsafe {
            use crate::ffi_ptr_ext::FfiPtrExt;
            (*self.as_type_ptr())
                .tp_mro
                .assume_borrowed(self.py())
                .to_owned()
                .downcast_into_unchecked()
        };

        mro
    }

    fn bases(&self) -> Bound<'py, PyTuple> {
        #[cfg(any(Py_LIMITED_API, PyPy))]
        let bases = self
            .getattr(intern!(self.py(), "__bases__"))
            .expect("Cannot get `__bases__` from object.")
            .extract()
            .expect("Unexpected type in `__bases__` attribute.");

        #[cfg(not(any(Py_LIMITED_API, PyPy)))]
        let bases = unsafe {
            use crate::ffi_ptr_ext::FfiPtrExt;
            (*self.as_type_ptr())
                .tp_bases
                .assume_borrowed(self.py())
                .to_owned()
                .downcast_into_unchecked()
        };

        bases
    }
}

#[cfg(test)]
mod tests {
    use crate::types::{PyAnyMethods, PyBool, PyInt, PyModule, PyTuple, PyType, PyTypeMethods};
    use crate::PyAny;
    use crate::Python;

    #[test]
    fn test_type_is_subclass() {
        Python::with_gil(|py| {
            let bool_type = py.get_type_bound::<PyBool>();
            let long_type = py.get_type_bound::<PyInt>();
            assert!(bool_type.is_subclass(&long_type).unwrap());
        });
    }

    #[test]
    fn test_type_is_subclass_of() {
        Python::with_gil(|py| {
            assert!(py
                .get_type_bound::<PyBool>()
                .is_subclass_of::<PyInt>()
                .unwrap());
        });
    }

    #[test]
    fn test_mro() {
        Python::with_gil(|py| {
            assert!(py
                .get_type_bound::<PyBool>()
                .mro()
                .eq(PyTuple::new_bound(
                    py,
                    [
                        py.get_type_bound::<PyBool>(),
                        py.get_type_bound::<PyInt>(),
                        py.get_type_bound::<PyAny>()
                    ]
                ))
                .unwrap());
        });
    }

    #[test]
    fn test_bases_bool() {
        Python::with_gil(|py| {
            assert!(py
                .get_type_bound::<PyBool>()
                .bases()
                .eq(PyTuple::new_bound(py, [py.get_type_bound::<PyInt>()]))
                .unwrap());
        });
    }

    #[test]
    fn test_bases_object() {
        Python::with_gil(|py| {
            assert!(py
                .get_type_bound::<PyAny>()
                .bases()
                .eq(PyTuple::empty_bound(py))
                .unwrap());
        });
    }

    #[test]
    fn test_type_names_standard() {
        Python::with_gil(|py| {
            let module = PyModule::from_code_bound(
                py,
                r#"
class MyClass:
    pass
"#,
                file!(),
                "test_module",
            )
            .expect("module create failed");

            let my_class = module.getattr("MyClass").unwrap();
            let my_class_type = my_class.downcast_into::<PyType>().unwrap();
            assert_eq!(my_class_type.name().unwrap(), "MyClass");
            assert_eq!(my_class_type.qualname().unwrap(), "MyClass");
            assert_eq!(my_class_type.module().unwrap(), "test_module");
            assert_eq!(
                my_class_type.fully_qualified_name().unwrap(),
                "test_module.MyClass"
            );
        });
    }

    #[test]
    fn test_type_names_builtin() {
        Python::with_gil(|py| {
            let bool_type = py.get_type_bound::<PyBool>();
            assert_eq!(bool_type.name().unwrap(), "bool");
            assert_eq!(bool_type.qualname().unwrap(), "bool");
            assert_eq!(bool_type.module().unwrap(), "builtins");
            assert_eq!(bool_type.fully_qualified_name().unwrap(), "bool");
        });
    }

    #[test]
    fn test_type_names_nested() {
        Python::with_gil(|py| {
            let module = PyModule::from_code_bound(
                py,
                r#"
class OuterClass:
    class InnerClass:
        pass
"#,
                file!(),
                "test_module",
            )
            .expect("module create failed");

            let outer_class = module.getattr("OuterClass").unwrap();
            let inner_class = outer_class.getattr("InnerClass").unwrap();
            let inner_class_type = inner_class.downcast_into::<PyType>().unwrap();
            assert_eq!(inner_class_type.name().unwrap(), "InnerClass");
            assert_eq!(
                inner_class_type.qualname().unwrap(),
                "OuterClass.InnerClass"
            );
            assert_eq!(inner_class_type.module().unwrap(), "test_module");
            assert_eq!(
                inner_class_type.fully_qualified_name().unwrap(),
                "test_module.OuterClass.InnerClass"
            );
        });
    }
}