-
Notifications
You must be signed in to change notification settings - Fork 677
/
typeobject.rs
64 lines (55 loc) · 2.06 KB
/
typeobject.rs
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
// Copyright (c) 2017-present PyO3 Project and Contributors
//
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use crate::err::{self, PyResult};
use crate::type_object::PyTypeObject;
use crate::{ffi, AsPyPointer, PyAny, Python};
/// Represents a reference to a Python `type object`.
#[repr(transparent)]
pub struct PyType(PyAny);
pyobject_native_type_core!(PyType, ffi::PyType_Type, #checkfunction=ffi::PyType_Check);
impl PyType {
/// Creates a new type object.
#[inline]
pub fn new<T: PyTypeObject>(py: Python) -> &PyType {
T::type_object(py)
}
/// Retrieves the underlying FFI pointer associated with this Python object.
#[inline]
pub fn as_type_ptr(&self) -> *mut ffi::PyTypeObject {
self.as_ptr() as *mut ffi::PyTypeObject
}
/// Retrieves the `PyType` instance for the given FFI pointer.
///
/// # Safety
/// - The pointer must be non-null.
/// - The pointer must be valid for the entire of the lifetime for which the reference is used.
#[inline]
pub unsafe fn from_type_ptr(py: Python, p: *mut ffi::PyTypeObject) -> &PyType {
py.from_borrowed_ptr(p as *mut ffi::PyObject)
}
/// Gets the name of the `PyType`.
pub fn name(&self) -> PyResult<&str> {
self.getattr("__qualname__")?.extract()
}
/// Checks whether `self` is subclass of type `T`.
///
/// Equivalent to Python's `issubclass` function.
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()) };
err::error_on_minusone(self.py(), result)?;
Ok(result == 1)
}
/// Check whether `obj` is an instance of `self`.
///
/// Equivalent to Python's `isinstance` function.
pub fn is_instance<T: AsPyPointer>(&self, obj: &T) -> PyResult<bool> {
let result = unsafe { ffi::PyObject_IsInstance(obj.as_ptr(), self.as_ptr()) };
err::error_on_minusone(self.py(), result)?;
Ok(result == 1)
}
}