use crate::err::{PyErr, PyResult};
use crate::instance::PyNativeType;
use crate::type_object::PyTypeObject;
use crate::{ffi, AsPyPointer, PyAny, Python};
#[repr(transparent)]
pub struct PyType(PyAny);
pyobject_native_type_core!(PyType, ffi::PyType_Type, #checkfunction=ffi::PyType_Check);
impl PyType {
#[inline]
pub fn new<T: PyTypeObject>(py: Python) -> &PyType {
T::type_object(py)
}
#[inline]
pub 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) -> PyResult<&str> {
self.getattr("__qualname__")?.extract()
}
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)
}
}
}