-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnone.rs
More file actions
85 lines (72 loc) · 2.28 KB
/
none.rs
File metadata and controls
85 lines (72 loc) · 2.28 KB
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
use crate::ffi_ptr_ext::FfiPtrExt;
#[cfg(feature = "experimental-inspect")]
use crate::inspect::TypeHint;
use crate::{ffi, types::any::PyAnyMethods, Borrowed, Bound, PyAny, PyTypeInfo, Python};
/// Represents the Python `None` object.
///
/// Values of this type are accessed via PyO3's smart pointers, e.g. as
/// [`Py<PyNone>`][crate::Py] or [`Bound<'py, PyNone>`][Bound].
#[repr(transparent)]
pub struct PyNone(PyAny);
pyobject_native_type_named!(PyNone);
impl PyNone {
/// Returns the `None` object.
#[inline]
pub fn get(py: Python<'_>) -> Borrowed<'_, '_, PyNone> {
// SAFETY: `Py_None` is a global singleton which is known to be the None object
unsafe {
ffi::Py_None()
.assume_borrowed_unchecked(py)
.cast_unchecked()
}
}
}
unsafe impl PyTypeInfo for PyNone {
const NAME: &'static str = "NoneType";
const MODULE: Option<&'static str> = None;
#[cfg(feature = "experimental-inspect")]
const TYPE_HINT: TypeHint = TypeHint::builtin("None");
fn type_object_raw(_py: Python<'_>) -> *mut ffi::PyTypeObject {
unsafe { ffi::Py_TYPE(ffi::Py_None()) }
}
#[inline]
fn is_type_of(object: &Bound<'_, PyAny>) -> bool {
// NoneType is not usable as a base type
Self::is_exact_type_of(object)
}
#[inline]
fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool {
object.is(&**Self::get(object.py()))
}
}
#[cfg(test)]
mod tests {
use crate::types::any::PyAnyMethods;
use crate::types::{PyDict, PyNone};
use crate::{PyTypeInfo, Python};
#[test]
fn test_none_is_itself() {
Python::attach(|py| {
assert!(PyNone::get(py).is_instance_of::<PyNone>());
assert!(PyNone::get(py).is_exact_instance_of::<PyNone>());
})
}
#[test]
fn test_none_type_object_consistent() {
Python::attach(|py| {
assert!(PyNone::get(py).get_type().is(PyNone::type_object(py)));
})
}
#[test]
fn test_none_is_none() {
Python::attach(|py| {
assert!(PyNone::get(py).cast::<PyNone>().unwrap().is_none());
})
}
#[test]
fn test_dict_is_not_none() {
Python::attach(|py| {
assert!(PyDict::new(py).cast::<PyNone>().is_err());
})
}
}