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
use crate::err::{PyErr, PyResult};
use crate::instance::PyNativeType;
use crate::type_object::PyTypeObject;
use crate::{ffi, AsPyPointer, PyAny, Python};
use std::borrow::Cow;
use std::ffi::CStr;
#[repr(transparent)]
pub struct PyType(PyAny);
pyobject_native_var_type!(PyType, ffi::PyType_Type, ffi::PyType_Check);
impl PyType {
    
    #[inline]
    pub fn new<T: PyTypeObject>(py: Python) -> &PyType {
        T::type_object(py)
    }
    
    #[inline]
    pub unsafe fn as_type_ptr(&self) -> *mut ffi::PyTypeObject {
        self.as_ptr() as *mut ffi::PyTypeObject
    }
    
    
    
    #[inline]
    pub unsafe fn from_type_ptr(py: Python, p: *mut ffi::PyTypeObject) -> &PyType {
        py.from_borrowed_ptr(p as *mut ffi::PyObject)
    }
    
    pub fn name(&self) -> Cow<str> {
        unsafe { CStr::from_ptr((*self.as_type_ptr()).tp_name).to_string_lossy() }
    }
    
    
    
    pub fn is_subclass<T>(&self) -> PyResult<bool>
    where
        T: PyTypeObject,
    {
        let result =
            unsafe { ffi::PyObject_IsSubclass(self.as_ptr(), T::type_object(self.py()).as_ptr()) };
        if result == -1 {
            Err(PyErr::fetch(self.py()))
        } else if result == 1 {
            Ok(true)
        } else {
            Ok(false)
        }
    }
    
    
    
    pub fn is_instance<T: AsPyPointer>(&self, obj: &T) -> PyResult<bool> {
        let result = unsafe { ffi::PyObject_IsInstance(obj.as_ptr(), self.as_ptr()) };
        if result == -1 {
            Err(PyErr::fetch(self.py()))
        } else if result == 1 {
            Ok(true)
        } else {
            Ok(false)
        }
    }
}