pyo3/types/
ellipsis.rs

1use crate::{
2    ffi, ffi_ptr_ext::FfiPtrExt, types::any::PyAnyMethods, Borrowed, Bound, PyAny, PyTypeInfo,
3    Python,
4};
5
6/// Represents the Python `Ellipsis` object.
7///
8/// Values of this type are accessed via PyO3's smart pointers, e.g. as
9/// [`Py<PyEllipsis>`][crate::Py] or [`Bound<'py, PyEllipsis>`][Bound].
10#[repr(transparent)]
11pub struct PyEllipsis(PyAny);
12
13pyobject_native_type_named!(PyEllipsis);
14pyobject_native_type_extract!(PyEllipsis);
15
16impl PyEllipsis {
17    /// Returns the `Ellipsis` object.
18    #[cfg(feature = "gil-refs")]
19    #[deprecated(
20        since = "0.21.0",
21        note = "`PyEllipsis::get` will be replaced by `PyEllipsis::get_bound` in a future PyO3 version"
22    )]
23    #[inline]
24    pub fn get(py: Python<'_>) -> &PyEllipsis {
25        Self::get_bound(py).into_gil_ref()
26    }
27
28    /// Returns the `Ellipsis` object.
29    #[inline]
30    pub fn get_bound(py: Python<'_>) -> Borrowed<'_, '_, PyEllipsis> {
31        unsafe { ffi::Py_Ellipsis().assume_borrowed(py).downcast_unchecked() }
32    }
33}
34
35unsafe impl PyTypeInfo for PyEllipsis {
36    const NAME: &'static str = "ellipsis";
37
38    const MODULE: Option<&'static str> = None;
39
40    fn type_object_raw(_py: Python<'_>) -> *mut ffi::PyTypeObject {
41        unsafe { ffi::Py_TYPE(ffi::Py_Ellipsis()) }
42    }
43
44    #[inline]
45    fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool {
46        // ellipsis is not usable as a base type
47        Self::is_exact_type_of_bound(object)
48    }
49
50    #[inline]
51    fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool {
52        object.is(&**Self::get_bound(object.py()))
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use crate::types::any::PyAnyMethods;
59    use crate::types::{PyDict, PyEllipsis};
60    use crate::{PyTypeInfo, Python};
61
62    #[test]
63    fn test_ellipsis_is_itself() {
64        Python::with_gil(|py| {
65            assert!(PyEllipsis::get_bound(py).is_instance_of::<PyEllipsis>());
66            assert!(PyEllipsis::get_bound(py).is_exact_instance_of::<PyEllipsis>());
67        })
68    }
69
70    #[test]
71    fn test_ellipsis_type_object_consistent() {
72        Python::with_gil(|py| {
73            assert!(PyEllipsis::get_bound(py)
74                .get_type()
75                .is(&PyEllipsis::type_object_bound(py)));
76        })
77    }
78
79    #[test]
80    fn test_dict_is_not_ellipsis() {
81        Python::with_gil(|py| {
82            assert!(PyDict::new_bound(py).downcast::<PyEllipsis>().is_err());
83        })
84    }
85}