pyo3/types/
any.rs

1use crate::class::basic::CompareOp;
2use crate::conversion::{private, AsPyPointer, FromPyObjectBound, IntoPy, ToPyObject};
3use crate::err::{DowncastError, DowncastIntoError, PyErr, PyResult};
4use crate::exceptions::{PyAttributeError, PyTypeError};
5use crate::ffi_ptr_ext::FfiPtrExt;
6use crate::instance::Bound;
7use crate::internal::get_slot::TP_DESCR_GET;
8use crate::internal_tricks::ptr_from_ref;
9use crate::py_result_ext::PyResultExt;
10use crate::type_object::{PyTypeCheck, PyTypeInfo};
11#[cfg(not(any(PyPy, GraalPy)))]
12use crate::types::PySuper;
13use crate::types::{PyDict, PyIterator, PyList, PyString, PyTuple, PyType};
14use crate::{err, ffi, Py, Python};
15#[cfg(feature = "gil-refs")]
16use crate::{err::PyDowncastError, type_object::HasPyGilRef, PyNativeType};
17use std::cell::UnsafeCell;
18use std::cmp::Ordering;
19use std::os::raw::c_int;
20
21/// Represents any Python object.
22///
23/// Values of this type are accessed via PyO3's smart pointers, e.g. as
24/// [`Py<PyAny>`][crate::Py] or [`Bound<'py, PyAny>`][Bound].
25///
26/// For APIs available on all Python objects, see the [`PyAnyMethods`] trait which is implemented for
27/// [`Bound<'py, PyAny>`][Bound].
28///
29/// See
30#[doc = concat!("[the guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html#concrete-python-types)")]
31/// for an explanation of the different Python object types.
32#[repr(transparent)]
33pub struct PyAny(UnsafeCell<ffi::PyObject>);
34
35unsafe impl AsPyPointer for PyAny {
36    #[inline]
37    fn as_ptr(&self) -> *mut ffi::PyObject {
38        self.0.get()
39    }
40}
41
42#[allow(non_snake_case)]
43// Copied here as the macro does not accept deprecated functions.
44// Originally ffi::object::PyObject_Check, but this is not in the Python C API.
45fn PyObject_Check(_: *mut ffi::PyObject) -> c_int {
46    1
47}
48
49pyobject_native_type_base!(PyAny);
50
51pyobject_native_type_info!(
52    PyAny,
53    pyobject_native_static_type_object!(ffi::PyBaseObject_Type),
54    Some("builtins"),
55    #checkfunction=PyObject_Check
56);
57
58pyobject_native_type_extract!(PyAny);
59
60pyobject_native_type_sized!(PyAny, ffi::PyObject);
61
62#[cfg(feature = "gil-refs")]
63impl PyAny {
64    /// Returns whether `self` and `other` point to the same object. To compare
65    /// the equality of two objects (the `==` operator), use [`eq`](PyAny::eq).
66    ///
67    /// This is equivalent to the Python expression `self is other`.
68    #[inline]
69    pub fn is<T: AsPyPointer>(&self, other: &T) -> bool {
70        self.as_borrowed().is(other)
71    }
72
73    /// Determines whether this object has the given attribute.
74    ///
75    /// This is equivalent to the Python expression `hasattr(self, attr_name)`.
76    ///
77    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
78    /// to intern `attr_name`.
79    ///
80    /// # Example: `intern!`ing the attribute name
81    ///
82    /// ```
83    /// # use pyo3::{prelude::*, intern};
84    /// #
85    /// #[pyfunction]
86    /// fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> {
87    ///     sys.hasattr(intern!(sys.py(), "version"))
88    /// }
89    /// #
90    /// # Python::with_gil(|py| {
91    /// #    let sys = py.import_bound("sys").unwrap();
92    /// #    has_version(&sys).unwrap();
93    /// # });
94    /// ```
95    pub fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
96    where
97        N: IntoPy<Py<PyString>>,
98    {
99        self.as_borrowed().hasattr(attr_name)
100    }
101
102    /// Retrieves an attribute value.
103    ///
104    /// This is equivalent to the Python expression `self.attr_name`.
105    ///
106    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
107    /// to intern `attr_name`.
108    ///
109    /// # Example: `intern!`ing the attribute name
110    ///
111    /// ```
112    /// # use pyo3::{prelude::*, intern};
113    /// #
114    /// #[pyfunction]
115    /// fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> {
116    ///     sys.getattr(intern!(sys.py(), "version"))
117    /// }
118    /// #
119    /// # Python::with_gil(|py| {
120    /// #    let sys = py.import_bound("sys").unwrap();
121    /// #    version(&sys).unwrap();
122    /// # });
123    /// ```
124    pub fn getattr<N>(&self, attr_name: N) -> PyResult<&PyAny>
125    where
126        N: IntoPy<Py<PyString>>,
127    {
128        self.as_borrowed()
129            .getattr(attr_name)
130            .map(Bound::into_gil_ref)
131    }
132
133    /// Sets an attribute value.
134    ///
135    /// This is equivalent to the Python expression `self.attr_name = value`.
136    ///
137    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
138    /// to intern `name`.
139    ///
140    /// # Example: `intern!`ing the attribute name
141    ///
142    /// ```
143    /// # use pyo3::{prelude::*, intern};
144    /// #
145    /// #[pyfunction]
146    /// fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> {
147    ///     ob.setattr(intern!(ob.py(), "answer"), 42)
148    /// }
149    /// #
150    /// # Python::with_gil(|py| {
151    /// #    let ob = PyModule::new_bound(py, "empty").unwrap();
152    /// #    set_answer(&ob).unwrap();
153    /// # });
154    /// ```
155    pub fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
156    where
157        N: IntoPy<Py<PyString>>,
158        V: ToPyObject,
159    {
160        self.as_borrowed().setattr(attr_name, value)
161    }
162
163    /// Deletes an attribute.
164    ///
165    /// This is equivalent to the Python statement `del self.attr_name`.
166    ///
167    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
168    /// to intern `attr_name`.
169    pub fn delattr<N>(&self, attr_name: N) -> PyResult<()>
170    where
171        N: IntoPy<Py<PyString>>,
172    {
173        self.as_borrowed().delattr(attr_name)
174    }
175
176    /// Returns an [`Ordering`] between `self` and `other`.
177    ///
178    /// This is equivalent to the following Python code:
179    /// ```python
180    /// if self == other:
181    ///     return Equal
182    /// elif a < b:
183    ///     return Less
184    /// elif a > b:
185    ///     return Greater
186    /// else:
187    ///     raise TypeError("PyAny::compare(): All comparisons returned false")
188    /// ```
189    ///
190    /// # Examples
191    ///
192    /// ```rust
193    /// use pyo3::prelude::*;
194    /// use pyo3::types::PyFloat;
195    /// use std::cmp::Ordering;
196    ///
197    /// # fn main() -> PyResult<()> {
198    /// Python::with_gil(|py| -> PyResult<()> {
199    ///     let a = PyFloat::new_bound(py, 0_f64);
200    ///     let b = PyFloat::new_bound(py, 42_f64);
201    ///     assert_eq!(a.compare(b)?, Ordering::Less);
202    ///     Ok(())
203    /// })?;
204    /// # Ok(())}
205    /// ```
206    ///
207    /// It will return `PyErr` for values that cannot be compared:
208    ///
209    /// ```rust
210    /// use pyo3::prelude::*;
211    /// use pyo3::types::{PyFloat, PyString};
212    ///
213    /// # fn main() -> PyResult<()> {
214    /// Python::with_gil(|py| -> PyResult<()> {
215    ///     let a = PyFloat::new_bound(py, 0_f64);
216    ///     let b = PyString::new_bound(py, "zero");
217    ///     assert!(a.compare(b).is_err());
218    ///     Ok(())
219    /// })?;
220    /// # Ok(())}
221    /// ```
222    pub fn compare<O>(&self, other: O) -> PyResult<Ordering>
223    where
224        O: ToPyObject,
225    {
226        self.as_borrowed().compare(other)
227    }
228
229    /// Tests whether two Python objects obey a given [`CompareOp`].
230    ///
231    /// [`lt`](Self::lt), [`le`](Self::le), [`eq`](Self::eq), [`ne`](Self::ne),
232    /// [`gt`](Self::gt) and [`ge`](Self::ge) are the specialized versions
233    /// of this function.
234    ///
235    /// Depending on the value of `compare_op`, this is equivalent to one of the
236    /// following Python expressions:
237    ///
238    /// | `compare_op` | Python expression |
239    /// | :---: | :----: |
240    /// | [`CompareOp::Eq`] | `self == other` |
241    /// | [`CompareOp::Ne`] | `self != other` |
242    /// | [`CompareOp::Lt`] | `self < other` |
243    /// | [`CompareOp::Le`] | `self <= other` |
244    /// | [`CompareOp::Gt`] | `self > other` |
245    /// | [`CompareOp::Ge`] | `self >= other` |
246    ///
247    /// # Examples
248    ///
249    /// ```rust
250    /// use pyo3::class::basic::CompareOp;
251    /// use pyo3::prelude::*;
252    /// use pyo3::types::PyInt;
253    ///
254    /// # fn main() -> PyResult<()> {
255    /// Python::with_gil(|py| -> PyResult<()> {
256    ///     let a: Bound<'_, PyInt> = 0_u8.into_py(py).into_bound(py).downcast_into()?;
257    ///     let b: Bound<'_, PyInt> = 42_u8.into_py(py).into_bound(py).downcast_into()?;
258    ///     assert!(a.rich_compare(b, CompareOp::Le)?.is_truthy()?);
259    ///     Ok(())
260    /// })?;
261    /// # Ok(())}
262    /// ```
263    pub fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<&PyAny>
264    where
265        O: ToPyObject,
266    {
267        self.as_borrowed()
268            .rich_compare(other, compare_op)
269            .map(Bound::into_gil_ref)
270    }
271
272    /// Tests whether this object is less than another.
273    ///
274    /// This is equivalent to the Python expression `self < other`.
275    pub fn lt<O>(&self, other: O) -> PyResult<bool>
276    where
277        O: ToPyObject,
278    {
279        self.as_borrowed().lt(other)
280    }
281
282    /// Tests whether this object is less than or equal to another.
283    ///
284    /// This is equivalent to the Python expression `self <= other`.
285    pub fn le<O>(&self, other: O) -> PyResult<bool>
286    where
287        O: ToPyObject,
288    {
289        self.as_borrowed().le(other)
290    }
291
292    /// Tests whether this object is equal to another.
293    ///
294    /// This is equivalent to the Python expression `self == other`.
295    pub fn eq<O>(&self, other: O) -> PyResult<bool>
296    where
297        O: ToPyObject,
298    {
299        self.as_borrowed().eq(other)
300    }
301
302    /// Tests whether this object is not equal to another.
303    ///
304    /// This is equivalent to the Python expression `self != other`.
305    pub fn ne<O>(&self, other: O) -> PyResult<bool>
306    where
307        O: ToPyObject,
308    {
309        self.as_borrowed().ne(other)
310    }
311
312    /// Tests whether this object is greater than another.
313    ///
314    /// This is equivalent to the Python expression `self > other`.
315    pub fn gt<O>(&self, other: O) -> PyResult<bool>
316    where
317        O: ToPyObject,
318    {
319        self.as_borrowed().gt(other)
320    }
321
322    /// Tests whether this object is greater than or equal to another.
323    ///
324    /// This is equivalent to the Python expression `self >= other`.
325    pub fn ge<O>(&self, other: O) -> PyResult<bool>
326    where
327        O: ToPyObject,
328    {
329        self.as_borrowed().ge(other)
330    }
331
332    /// Determines whether this object appears callable.
333    ///
334    /// This is equivalent to Python's [`callable()`][1] function.
335    ///
336    /// # Examples
337    ///
338    /// ```rust
339    /// use pyo3::prelude::*;
340    ///
341    /// # fn main() -> PyResult<()> {
342    /// Python::with_gil(|py| -> PyResult<()> {
343    ///     let builtins = PyModule::import_bound(py, "builtins")?;
344    ///     let print = builtins.getattr("print")?;
345    ///     assert!(print.is_callable());
346    ///     Ok(())
347    /// })?;
348    /// # Ok(())}
349    /// ```
350    ///
351    /// This is equivalent to the Python statement `assert callable(print)`.
352    ///
353    /// Note that unless an API needs to distinguish between callable and
354    /// non-callable objects, there is no point in checking for callability.
355    /// Instead, it is better to just do the call and handle potential
356    /// exceptions.
357    ///
358    /// [1]: https://docs.python.org/3/library/functions.html#callable
359    pub fn is_callable(&self) -> bool {
360        self.as_borrowed().is_callable()
361    }
362
363    /// Calls the object.
364    ///
365    /// This is equivalent to the Python expression `self(*args, **kwargs)`.
366    ///
367    /// # Examples
368    ///
369    /// ```rust
370    /// use pyo3::prelude::*;
371    /// use pyo3::types::PyDict;
372    ///
373    /// const CODE: &str = r#"
374    /// def function(*args, **kwargs):
375    ///     assert args == ("hello",)
376    ///     assert kwargs == {"cruel": "world"}
377    ///     return "called with args and kwargs"
378    /// "#;
379    ///
380    /// # fn main() -> PyResult<()> {
381    /// Python::with_gil(|py| {
382    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
383    ///     let fun = module.getattr("function")?;
384    ///     let args = ("hello",);
385    ///     let kwargs = PyDict::new_bound(py);
386    ///     kwargs.set_item("cruel", "world")?;
387    ///     let result = fun.call(args, Some(&kwargs))?;
388    ///     assert_eq!(result.extract::<String>()?, "called with args and kwargs");
389    ///     Ok(())
390    /// })
391    /// # }
392    /// ```
393    pub fn call(
394        &self,
395        args: impl IntoPy<Py<PyTuple>>,
396        kwargs: Option<&PyDict>,
397    ) -> PyResult<&PyAny> {
398        self.as_borrowed()
399            .call(args, kwargs.map(PyDict::as_borrowed).as_deref())
400            .map(Bound::into_gil_ref)
401    }
402
403    /// Calls the object without arguments.
404    ///
405    /// This is equivalent to the Python expression `self()`.
406    ///
407    /// # Examples
408    ///
409    /// ```no_run
410    /// use pyo3::prelude::*;
411    ///
412    /// # fn main() -> PyResult<()> {
413    /// Python::with_gil(|py| -> PyResult<()> {
414    ///     let module = PyModule::import_bound(py, "builtins")?;
415    ///     let help = module.getattr("help")?;
416    ///     help.call0()?;
417    ///     Ok(())
418    /// })?;
419    /// # Ok(())}
420    /// ```
421    ///
422    /// This is equivalent to the Python expression `help()`.
423    pub fn call0(&self) -> PyResult<&PyAny> {
424        self.as_borrowed().call0().map(Bound::into_gil_ref)
425    }
426
427    /// Calls the object with only positional arguments.
428    ///
429    /// This is equivalent to the Python expression `self(*args)`.
430    ///
431    /// # Examples
432    ///
433    /// ```rust
434    /// use pyo3::prelude::*;
435    ///
436    /// const CODE: &str = r#"
437    /// def function(*args, **kwargs):
438    ///     assert args == ("hello",)
439    ///     assert kwargs == {}
440    ///     return "called with args"
441    /// "#;
442    ///
443    /// # fn main() -> PyResult<()> {
444    /// Python::with_gil(|py| {
445    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
446    ///     let fun = module.getattr("function")?;
447    ///     let args = ("hello",);
448    ///     let result = fun.call1(args)?;
449    ///     assert_eq!(result.extract::<String>()?, "called with args");
450    ///     Ok(())
451    /// })
452    /// # }
453    /// ```
454    pub fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
455        self.as_borrowed().call1(args).map(Bound::into_gil_ref)
456    }
457
458    /// Calls a method on the object.
459    ///
460    /// This is equivalent to the Python expression `self.name(*args, **kwargs)`.
461    ///
462    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
463    /// to intern `name`.
464    ///
465    /// # Examples
466    ///
467    /// ```rust
468    /// use pyo3::prelude::*;
469    /// use pyo3::types::PyDict;
470    ///
471    /// const CODE: &str = r#"
472    /// class A:
473    ///     def method(self, *args, **kwargs):
474    ///         assert args == ("hello",)
475    ///         assert kwargs == {"cruel": "world"}
476    ///         return "called with args and kwargs"
477    /// a = A()
478    /// "#;
479    ///
480    /// # fn main() -> PyResult<()> {
481    /// Python::with_gil(|py| {
482    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
483    ///     let instance = module.getattr("a")?;
484    ///     let args = ("hello",);
485    ///     let kwargs = PyDict::new_bound(py);
486    ///     kwargs.set_item("cruel", "world")?;
487    ///     let result = instance.call_method("method", args, Some(&kwargs))?;
488    ///     assert_eq!(result.extract::<String>()?, "called with args and kwargs");
489    ///     Ok(())
490    /// })
491    /// # }
492    /// ```
493    pub fn call_method<N, A>(&self, name: N, args: A, kwargs: Option<&PyDict>) -> PyResult<&PyAny>
494    where
495        N: IntoPy<Py<PyString>>,
496        A: IntoPy<Py<PyTuple>>,
497    {
498        self.as_borrowed()
499            .call_method(name, args, kwargs.map(PyDict::as_borrowed).as_deref())
500            .map(Bound::into_gil_ref)
501    }
502
503    /// Calls a method on the object without arguments.
504    ///
505    /// This is equivalent to the Python expression `self.name()`.
506    ///
507    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
508    /// to intern `name`.
509    ///
510    /// # Examples
511    ///
512    /// ```rust
513    /// use pyo3::prelude::*;
514    ///
515    /// const CODE: &str = r#"
516    /// class A:
517    ///     def method(self, *args, **kwargs):
518    ///         assert args == ()
519    ///         assert kwargs == {}
520    ///         return "called with no arguments"
521    /// a = A()
522    /// "#;
523    ///
524    /// # fn main() -> PyResult<()> {
525    /// Python::with_gil(|py| {
526    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
527    ///     let instance = module.getattr("a")?;
528    ///     let result = instance.call_method0("method")?;
529    ///     assert_eq!(result.extract::<String>()?, "called with no arguments");
530    ///     Ok(())
531    /// })
532    /// # }
533    /// ```
534    pub fn call_method0<N>(&self, name: N) -> PyResult<&PyAny>
535    where
536        N: IntoPy<Py<PyString>>,
537    {
538        self.as_borrowed()
539            .call_method0(name)
540            .map(Bound::into_gil_ref)
541    }
542
543    /// Calls a method on the object with only positional arguments.
544    ///
545    /// This is equivalent to the Python expression `self.name(*args)`.
546    ///
547    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
548    /// to intern `name`.
549    ///
550    /// # Examples
551    ///
552    /// ```rust
553    /// use pyo3::prelude::*;
554    ///
555    /// const CODE: &str = r#"
556    /// class A:
557    ///     def method(self, *args, **kwargs):
558    ///         assert args == ("hello",)
559    ///         assert kwargs == {}
560    ///         return "called with args"
561    /// a = A()
562    /// "#;
563    ///
564    /// # fn main() -> PyResult<()> {
565    /// Python::with_gil(|py| {
566    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
567    ///     let instance = module.getattr("a")?;
568    ///     let args = ("hello",);
569    ///     let result = instance.call_method1("method", args)?;
570    ///     assert_eq!(result.extract::<String>()?, "called with args");
571    ///     Ok(())
572    /// })
573    /// # }
574    /// ```
575    pub fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<&PyAny>
576    where
577        N: IntoPy<Py<PyString>>,
578        A: IntoPy<Py<PyTuple>>,
579    {
580        self.as_borrowed()
581            .call_method1(name, args)
582            .map(Bound::into_gil_ref)
583    }
584
585    /// Returns whether the object is considered to be true.
586    ///
587    /// This is equivalent to the Python expression `bool(self)`.
588    #[deprecated(since = "0.21.0", note = "use `.is_truthy()` instead")]
589    pub fn is_true(&self) -> PyResult<bool> {
590        self.is_truthy()
591    }
592
593    /// Returns whether the object is considered to be true.
594    ///
595    /// This applies truth value testing equivalent to the Python expression `bool(self)`.
596    pub fn is_truthy(&self) -> PyResult<bool> {
597        self.as_borrowed().is_truthy()
598    }
599
600    /// Returns whether the object is considered to be None.
601    ///
602    /// This is equivalent to the Python expression `self is None`.
603    #[inline]
604    pub fn is_none(&self) -> bool {
605        self.as_borrowed().is_none()
606    }
607
608    /// Returns whether the object is Ellipsis, e.g. `...`.
609    ///
610    /// This is equivalent to the Python expression `self is ...`.
611    #[deprecated(since = "0.20.0", note = "use `.is(py.Ellipsis())` instead")]
612    pub fn is_ellipsis(&self) -> bool {
613        self.as_borrowed().is_ellipsis()
614    }
615
616    /// Returns true if the sequence or mapping has a length of 0.
617    ///
618    /// This is equivalent to the Python expression `len(self) == 0`.
619    pub fn is_empty(&self) -> PyResult<bool> {
620        self.as_borrowed().is_empty()
621    }
622
623    /// Gets an item from the collection.
624    ///
625    /// This is equivalent to the Python expression `self[key]`.
626    pub fn get_item<K>(&self, key: K) -> PyResult<&PyAny>
627    where
628        K: ToPyObject,
629    {
630        self.as_borrowed().get_item(key).map(Bound::into_gil_ref)
631    }
632
633    /// Sets a collection item value.
634    ///
635    /// This is equivalent to the Python expression `self[key] = value`.
636    pub fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
637    where
638        K: ToPyObject,
639        V: ToPyObject,
640    {
641        self.as_borrowed().set_item(key, value)
642    }
643
644    /// Deletes an item from the collection.
645    ///
646    /// This is equivalent to the Python expression `del self[key]`.
647    pub fn del_item<K>(&self, key: K) -> PyResult<()>
648    where
649        K: ToPyObject,
650    {
651        self.as_borrowed().del_item(key)
652    }
653
654    /// Takes an object and returns an iterator for it.
655    ///
656    /// This is typically a new iterator but if the argument is an iterator,
657    /// this returns itself.
658    pub fn iter(&self) -> PyResult<&PyIterator> {
659        self.as_borrowed().iter().map(Bound::into_gil_ref)
660    }
661
662    /// Returns the Python type object for this object's type.
663    pub fn get_type(&self) -> &PyType {
664        self.as_borrowed().get_type().into_gil_ref()
665    }
666
667    /// Returns the Python type pointer for this object.
668    #[inline]
669    pub fn get_type_ptr(&self) -> *mut ffi::PyTypeObject {
670        self.as_borrowed().get_type_ptr()
671    }
672
673    /// Downcast this `PyAny` to a concrete Python type or pyclass.
674    ///
675    /// Note that you can often avoid downcasting yourself by just specifying
676    /// the desired type in function or method signatures.
677    /// However, manual downcasting is sometimes necessary.
678    ///
679    /// For extracting a Rust-only type, see [`PyAny::extract`](struct.PyAny.html#method.extract).
680    ///
681    /// # Example: Downcasting to a specific Python object
682    ///
683    /// ```rust
684    /// use pyo3::prelude::*;
685    /// use pyo3::types::{PyDict, PyList};
686    ///
687    /// Python::with_gil(|py| {
688    ///     let dict = PyDict::new_bound(py);
689    ///     assert!(dict.is_instance_of::<PyAny>());
690    ///     let any = dict.as_any();
691    ///
692    ///     assert!(any.downcast::<PyDict>().is_ok());
693    ///     assert!(any.downcast::<PyList>().is_err());
694    /// });
695    /// ```
696    ///
697    /// # Example: Getting a reference to a pyclass
698    ///
699    /// This is useful if you want to mutate a `PyObject` that
700    /// might actually be a pyclass.
701    ///
702    /// ```rust
703    /// # fn main() -> Result<(), pyo3::PyErr> {
704    /// use pyo3::prelude::*;
705    ///
706    /// #[pyclass]
707    /// struct Class {
708    ///     i: i32,
709    /// }
710    ///
711    /// Python::with_gil(|py| {
712    ///     let class = Py::new(py, Class { i: 0 }).unwrap().into_bound(py).into_any();
713    ///
714    ///     let class_bound: &Bound<'_, Class> = class.downcast()?;
715    ///
716    ///     class_bound.borrow_mut().i += 1;
717    ///
718    ///     // Alternatively you can get a `PyRefMut` directly
719    ///     let class_ref: PyRefMut<'_, Class> = class.extract()?;
720    ///     assert_eq!(class_ref.i, 1);
721    ///     Ok(())
722    /// })
723    /// # }
724    /// ```
725    #[inline]
726    pub fn downcast<T>(&self) -> Result<&T, PyDowncastError<'_>>
727    where
728        T: PyTypeCheck<AsRefTarget = T>,
729    {
730        if T::type_check(&self.as_borrowed()) {
731            // Safety: type_check is responsible for ensuring that the type is correct
732            Ok(unsafe { self.downcast_unchecked() })
733        } else {
734            Err(PyDowncastError::new(self, T::NAME))
735        }
736    }
737
738    /// Downcast this `PyAny` to a concrete Python type or pyclass (but not a subclass of it).
739    ///
740    /// It is almost always better to use [`PyAny::downcast`] because it accounts for Python
741    /// subtyping. Use this method only when you do not want to allow subtypes.
742    ///
743    /// The advantage of this method over [`PyAny::downcast`] is that it is faster. The implementation
744    /// of `downcast_exact` uses the equivalent of the Python expression `type(self) is T`, whereas
745    /// `downcast` uses `isinstance(self, T)`.
746    ///
747    /// For extracting a Rust-only type, see [`PyAny::extract`](struct.PyAny.html#method.extract).
748    ///
749    /// # Example: Downcasting to a specific Python object but not a subtype
750    ///
751    /// ```rust
752    /// use pyo3::prelude::*;
753    /// use pyo3::types::{PyBool, PyLong};
754    ///
755    /// Python::with_gil(|py| {
756    ///     let b = PyBool::new_bound(py, true);
757    ///     assert!(b.is_instance_of::<PyBool>());
758    ///     let any: &Bound<'_, PyAny> = b.as_any();
759    ///
760    ///     // `bool` is a subtype of `int`, so `downcast` will accept a `bool` as an `int`
761    ///     // but `downcast_exact` will not.
762    ///     assert!(any.downcast::<PyLong>().is_ok());
763    ///     assert!(any.downcast_exact::<PyLong>().is_err());
764    ///
765    ///     assert!(any.downcast_exact::<PyBool>().is_ok());
766    /// });
767    /// ```
768    #[inline]
769    pub fn downcast_exact<T>(&self) -> Result<&T, PyDowncastError<'_>>
770    where
771        T: PyTypeInfo<AsRefTarget = T>,
772    {
773        if T::is_exact_type_of_bound(&self.as_borrowed()) {
774            // Safety: type_check is responsible for ensuring that the type is correct
775            Ok(unsafe { self.downcast_unchecked() })
776        } else {
777            Err(PyDowncastError::new(self, T::NAME))
778        }
779    }
780
781    /// Converts this `PyAny` to a concrete Python type without checking validity.
782    ///
783    /// # Safety
784    ///
785    /// Callers must ensure that the type is valid or risk type confusion.
786    #[inline]
787    pub unsafe fn downcast_unchecked<T>(&self) -> &T
788    where
789        T: HasPyGilRef<AsRefTarget = T>,
790    {
791        &*(self.as_ptr() as *const T)
792    }
793
794    /// Extracts some type from the Python object.
795    ///
796    /// This is a wrapper function around
797    /// [`FromPyObject::extract()`](crate::FromPyObject::extract).
798    #[inline]
799    pub fn extract<'py, D>(&'py self) -> PyResult<D>
800    where
801        D: FromPyObjectBound<'py, 'py>,
802    {
803        FromPyObjectBound::from_py_object_bound(self.as_borrowed())
804    }
805
806    /// Returns the reference count for the Python object.
807    pub fn get_refcnt(&self) -> isize {
808        self.as_borrowed().get_refcnt()
809    }
810
811    /// Computes the "repr" representation of self.
812    ///
813    /// This is equivalent to the Python expression `repr(self)`.
814    pub fn repr(&self) -> PyResult<&PyString> {
815        self.as_borrowed().repr().map(Bound::into_gil_ref)
816    }
817
818    /// Computes the "str" representation of self.
819    ///
820    /// This is equivalent to the Python expression `str(self)`.
821    pub fn str(&self) -> PyResult<&PyString> {
822        self.as_borrowed().str().map(Bound::into_gil_ref)
823    }
824
825    /// Retrieves the hash code of self.
826    ///
827    /// This is equivalent to the Python expression `hash(self)`.
828    pub fn hash(&self) -> PyResult<isize> {
829        self.as_borrowed().hash()
830    }
831
832    /// Returns the length of the sequence or mapping.
833    ///
834    /// This is equivalent to the Python expression `len(self)`.
835    pub fn len(&self) -> PyResult<usize> {
836        self.as_borrowed().len()
837    }
838
839    /// Returns the list of attributes of this object.
840    ///
841    /// This is equivalent to the Python expression `dir(self)`.
842    pub fn dir(&self) -> PyResult<&PyList> {
843        self.as_borrowed().dir().map(Bound::into_gil_ref)
844    }
845
846    /// Checks whether this object is an instance of type `ty`.
847    ///
848    /// This is equivalent to the Python expression `isinstance(self, ty)`.
849    #[inline]
850    pub fn is_instance(&self, ty: &PyAny) -> PyResult<bool> {
851        self.as_borrowed().is_instance(&ty.as_borrowed())
852    }
853
854    /// Checks whether this object is an instance of exactly type `ty` (not a subclass).
855    ///
856    /// This is equivalent to the Python expression `type(self) is ty`.
857    #[inline]
858    pub fn is_exact_instance(&self, ty: &PyAny) -> bool {
859        self.as_borrowed().is_exact_instance(&ty.as_borrowed())
860    }
861
862    /// Checks whether this object is an instance of type `T`.
863    ///
864    /// This is equivalent to the Python expression `isinstance(self, T)`,
865    /// if the type `T` is known at compile time.
866    #[inline]
867    pub fn is_instance_of<T: PyTypeInfo>(&self) -> bool {
868        self.as_borrowed().is_instance_of::<T>()
869    }
870
871    /// Checks whether this object is an instance of exactly type `T`.
872    ///
873    /// This is equivalent to the Python expression `type(self) is T`,
874    /// if the type `T` is known at compile time.
875    #[inline]
876    pub fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool {
877        self.as_borrowed().is_exact_instance_of::<T>()
878    }
879
880    /// Determines if self contains `value`.
881    ///
882    /// This is equivalent to the Python expression `value in self`.
883    pub fn contains<V>(&self, value: V) -> PyResult<bool>
884    where
885        V: ToPyObject,
886    {
887        self.as_borrowed().contains(value)
888    }
889
890    /// Returns a GIL marker constrained to the lifetime of this type.
891    #[inline]
892    pub fn py(&self) -> Python<'_> {
893        PyNativeType::py(self)
894    }
895
896    /// Returns the raw FFI pointer represented by self.
897    ///
898    /// # Safety
899    ///
900    /// Callers are responsible for ensuring that the pointer does not outlive self.
901    ///
902    /// The reference is borrowed; callers should not decrease the reference count
903    /// when they are finished with the pointer.
904    #[inline]
905    pub fn as_ptr(&self) -> *mut ffi::PyObject {
906        ptr_from_ref(self) as *mut ffi::PyObject
907    }
908
909    /// Returns an owned raw FFI pointer represented by self.
910    ///
911    /// # Safety
912    ///
913    /// The reference is owned; when finished the caller should either transfer ownership
914    /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)).
915    #[inline]
916    pub fn into_ptr(&self) -> *mut ffi::PyObject {
917        // Safety: self.as_ptr() returns a valid non-null pointer
918        let ptr = self.as_ptr();
919        unsafe { ffi::Py_INCREF(ptr) };
920        ptr
921    }
922
923    /// Return a proxy object that delegates method calls to a parent or sibling class of type.
924    ///
925    /// This is equivalent to the Python expression `super()`
926    #[cfg(not(any(PyPy, GraalPy)))]
927    pub fn py_super(&self) -> PyResult<&PySuper> {
928        self.as_borrowed().py_super().map(Bound::into_gil_ref)
929    }
930}
931
932/// This trait represents the Python APIs which are usable on all Python objects.
933///
934/// It is recommended you import this trait via `use pyo3::prelude::*` rather than
935/// by importing this trait directly.
936#[doc(alias = "PyAny")]
937pub trait PyAnyMethods<'py>: crate::sealed::Sealed {
938    /// Returns whether `self` and `other` point to the same object. To compare
939    /// the equality of two objects (the `==` operator), use [`eq`](PyAnyMethods::eq).
940    ///
941    /// This is equivalent to the Python expression `self is other`.
942    fn is<T: AsPyPointer>(&self, other: &T) -> bool;
943
944    /// Determines whether this object has the given attribute.
945    ///
946    /// This is equivalent to the Python expression `hasattr(self, attr_name)`.
947    ///
948    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
949    /// to intern `attr_name`.
950    ///
951    /// # Example: `intern!`ing the attribute name
952    ///
953    /// ```
954    /// # use pyo3::{prelude::*, intern};
955    /// #
956    /// #[pyfunction]
957    /// fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> {
958    ///     sys.hasattr(intern!(sys.py(), "version"))
959    /// }
960    /// #
961    /// # Python::with_gil(|py| {
962    /// #    let sys = py.import_bound("sys").unwrap();
963    /// #    has_version(&sys).unwrap();
964    /// # });
965    /// ```
966    fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
967    where
968        N: IntoPy<Py<PyString>>;
969
970    /// Retrieves an attribute value.
971    ///
972    /// This is equivalent to the Python expression `self.attr_name`.
973    ///
974    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
975    /// to intern `attr_name`.
976    ///
977    /// # Example: `intern!`ing the attribute name
978    ///
979    /// ```
980    /// # use pyo3::{prelude::*, intern};
981    /// #
982    /// #[pyfunction]
983    /// fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> {
984    ///     sys.getattr(intern!(sys.py(), "version"))
985    /// }
986    /// #
987    /// # Python::with_gil(|py| {
988    /// #    let sys = py.import_bound("sys").unwrap();
989    /// #    version(&sys).unwrap();
990    /// # });
991    /// ```
992    fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
993    where
994        N: IntoPy<Py<PyString>>;
995
996    /// Sets an attribute value.
997    ///
998    /// This is equivalent to the Python expression `self.attr_name = value`.
999    ///
1000    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
1001    /// to intern `name`.
1002    ///
1003    /// # Example: `intern!`ing the attribute name
1004    ///
1005    /// ```
1006    /// # use pyo3::{prelude::*, intern};
1007    /// #
1008    /// #[pyfunction]
1009    /// fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> {
1010    ///     ob.setattr(intern!(ob.py(), "answer"), 42)
1011    /// }
1012    /// #
1013    /// # Python::with_gil(|py| {
1014    /// #    let ob = PyModule::new_bound(py, "empty").unwrap();
1015    /// #    set_answer(&ob).unwrap();
1016    /// # });
1017    /// ```
1018    fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
1019    where
1020        N: IntoPy<Py<PyString>>,
1021        V: ToPyObject;
1022
1023    /// Deletes an attribute.
1024    ///
1025    /// This is equivalent to the Python statement `del self.attr_name`.
1026    ///
1027    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
1028    /// to intern `attr_name`.
1029    fn delattr<N>(&self, attr_name: N) -> PyResult<()>
1030    where
1031        N: IntoPy<Py<PyString>>;
1032
1033    /// Returns an [`Ordering`] between `self` and `other`.
1034    ///
1035    /// This is equivalent to the following Python code:
1036    /// ```python
1037    /// if self == other:
1038    ///     return Equal
1039    /// elif a < b:
1040    ///     return Less
1041    /// elif a > b:
1042    ///     return Greater
1043    /// else:
1044    ///     raise TypeError("PyAny::compare(): All comparisons returned false")
1045    /// ```
1046    ///
1047    /// # Examples
1048    ///
1049    /// ```rust
1050    /// use pyo3::prelude::*;
1051    /// use pyo3::types::PyFloat;
1052    /// use std::cmp::Ordering;
1053    ///
1054    /// # fn main() -> PyResult<()> {
1055    /// Python::with_gil(|py| -> PyResult<()> {
1056    ///     let a = PyFloat::new_bound(py, 0_f64);
1057    ///     let b = PyFloat::new_bound(py, 42_f64);
1058    ///     assert_eq!(a.compare(b)?, Ordering::Less);
1059    ///     Ok(())
1060    /// })?;
1061    /// # Ok(())}
1062    /// ```
1063    ///
1064    /// It will return `PyErr` for values that cannot be compared:
1065    ///
1066    /// ```rust
1067    /// use pyo3::prelude::*;
1068    /// use pyo3::types::{PyFloat, PyString};
1069    ///
1070    /// # fn main() -> PyResult<()> {
1071    /// Python::with_gil(|py| -> PyResult<()> {
1072    ///     let a = PyFloat::new_bound(py, 0_f64);
1073    ///     let b = PyString::new_bound(py, "zero");
1074    ///     assert!(a.compare(b).is_err());
1075    ///     Ok(())
1076    /// })?;
1077    /// # Ok(())}
1078    /// ```
1079    fn compare<O>(&self, other: O) -> PyResult<Ordering>
1080    where
1081        O: ToPyObject;
1082
1083    /// Tests whether two Python objects obey a given [`CompareOp`].
1084    ///
1085    /// [`lt`](Self::lt), [`le`](Self::le), [`eq`](Self::eq), [`ne`](Self::ne),
1086    /// [`gt`](Self::gt) and [`ge`](Self::ge) are the specialized versions
1087    /// of this function.
1088    ///
1089    /// Depending on the value of `compare_op`, this is equivalent to one of the
1090    /// following Python expressions:
1091    ///
1092    /// | `compare_op` | Python expression |
1093    /// | :---: | :----: |
1094    /// | [`CompareOp::Eq`] | `self == other` |
1095    /// | [`CompareOp::Ne`] | `self != other` |
1096    /// | [`CompareOp::Lt`] | `self < other` |
1097    /// | [`CompareOp::Le`] | `self <= other` |
1098    /// | [`CompareOp::Gt`] | `self > other` |
1099    /// | [`CompareOp::Ge`] | `self >= other` |
1100    ///
1101    /// # Examples
1102    ///
1103    /// ```rust
1104    /// use pyo3::class::basic::CompareOp;
1105    /// use pyo3::prelude::*;
1106    /// use pyo3::types::PyInt;
1107    ///
1108    /// # fn main() -> PyResult<()> {
1109    /// Python::with_gil(|py| -> PyResult<()> {
1110    ///     let a: Bound<'_, PyInt> = 0_u8.into_py(py).into_bound(py).downcast_into()?;
1111    ///     let b: Bound<'_, PyInt> = 42_u8.into_py(py).into_bound(py).downcast_into()?;
1112    ///     assert!(a.rich_compare(b, CompareOp::Le)?.is_truthy()?);
1113    ///     Ok(())
1114    /// })?;
1115    /// # Ok(())}
1116    /// ```
1117    fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>>
1118    where
1119        O: ToPyObject;
1120
1121    /// Computes the negative of self.
1122    ///
1123    /// Equivalent to the Python expression `-self`.
1124    fn neg(&self) -> PyResult<Bound<'py, PyAny>>;
1125
1126    /// Computes the positive of self.
1127    ///
1128    /// Equivalent to the Python expression `+self`.
1129    fn pos(&self) -> PyResult<Bound<'py, PyAny>>;
1130
1131    /// Computes the absolute of self.
1132    ///
1133    /// Equivalent to the Python expression `abs(self)`.
1134    fn abs(&self) -> PyResult<Bound<'py, PyAny>>;
1135
1136    /// Computes `~self`.
1137    fn bitnot(&self) -> PyResult<Bound<'py, PyAny>>;
1138
1139    /// Tests whether this object is less than another.
1140    ///
1141    /// This is equivalent to the Python expression `self < other`.
1142    fn lt<O>(&self, other: O) -> PyResult<bool>
1143    where
1144        O: ToPyObject;
1145
1146    /// Tests whether this object is less than or equal to another.
1147    ///
1148    /// This is equivalent to the Python expression `self <= other`.
1149    fn le<O>(&self, other: O) -> PyResult<bool>
1150    where
1151        O: ToPyObject;
1152
1153    /// Tests whether this object is equal to another.
1154    ///
1155    /// This is equivalent to the Python expression `self == other`.
1156    fn eq<O>(&self, other: O) -> PyResult<bool>
1157    where
1158        O: ToPyObject;
1159
1160    /// Tests whether this object is not equal to another.
1161    ///
1162    /// This is equivalent to the Python expression `self != other`.
1163    fn ne<O>(&self, other: O) -> PyResult<bool>
1164    where
1165        O: ToPyObject;
1166
1167    /// Tests whether this object is greater than another.
1168    ///
1169    /// This is equivalent to the Python expression `self > other`.
1170    fn gt<O>(&self, other: O) -> PyResult<bool>
1171    where
1172        O: ToPyObject;
1173
1174    /// Tests whether this object is greater than or equal to another.
1175    ///
1176    /// This is equivalent to the Python expression `self >= other`.
1177    fn ge<O>(&self, other: O) -> PyResult<bool>
1178    where
1179        O: ToPyObject;
1180
1181    /// Computes `self + other`.
1182    fn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1183    where
1184        O: ToPyObject;
1185
1186    /// Computes `self - other`.
1187    fn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1188    where
1189        O: ToPyObject;
1190
1191    /// Computes `self * other`.
1192    fn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1193    where
1194        O: ToPyObject;
1195
1196    /// Computes `self @ other`.
1197    fn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1198    where
1199        O: ToPyObject;
1200
1201    /// Computes `self / other`.
1202    fn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1203    where
1204        O: ToPyObject;
1205
1206    /// Computes `self // other`.
1207    fn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1208    where
1209        O: ToPyObject;
1210
1211    /// Computes `self % other`.
1212    fn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1213    where
1214        O: ToPyObject;
1215
1216    /// Computes `divmod(self, other)`.
1217    fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1218    where
1219        O: ToPyObject;
1220
1221    /// Computes `self << other`.
1222    fn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1223    where
1224        O: ToPyObject;
1225
1226    /// Computes `self >> other`.
1227    fn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1228    where
1229        O: ToPyObject;
1230
1231    /// Computes `self ** other % modulus` (`pow(self, other, modulus)`).
1232    /// `py.None()` may be passed for the `modulus`.
1233    fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>
1234    where
1235        O1: ToPyObject,
1236        O2: ToPyObject;
1237
1238    /// Computes `self & other`.
1239    fn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1240    where
1241        O: ToPyObject;
1242
1243    /// Computes `self | other`.
1244    fn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1245    where
1246        O: ToPyObject;
1247
1248    /// Computes `self ^ other`.
1249    fn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1250    where
1251        O: ToPyObject;
1252
1253    /// Determines whether this object appears callable.
1254    ///
1255    /// This is equivalent to Python's [`callable()`][1] function.
1256    ///
1257    /// # Examples
1258    ///
1259    /// ```rust
1260    /// use pyo3::prelude::*;
1261    ///
1262    /// # fn main() -> PyResult<()> {
1263    /// Python::with_gil(|py| -> PyResult<()> {
1264    ///     let builtins = PyModule::import_bound(py, "builtins")?;
1265    ///     let print = builtins.getattr("print")?;
1266    ///     assert!(print.is_callable());
1267    ///     Ok(())
1268    /// })?;
1269    /// # Ok(())}
1270    /// ```
1271    ///
1272    /// This is equivalent to the Python statement `assert callable(print)`.
1273    ///
1274    /// Note that unless an API needs to distinguish between callable and
1275    /// non-callable objects, there is no point in checking for callability.
1276    /// Instead, it is better to just do the call and handle potential
1277    /// exceptions.
1278    ///
1279    /// [1]: https://docs.python.org/3/library/functions.html#callable
1280    fn is_callable(&self) -> bool;
1281
1282    /// Calls the object.
1283    ///
1284    /// This is equivalent to the Python expression `self(*args, **kwargs)`.
1285    ///
1286    /// # Examples
1287    ///
1288    /// ```rust
1289    /// use pyo3::prelude::*;
1290    /// use pyo3::types::PyDict;
1291    ///
1292    /// const CODE: &str = r#"
1293    /// def function(*args, **kwargs):
1294    ///     assert args == ("hello",)
1295    ///     assert kwargs == {"cruel": "world"}
1296    ///     return "called with args and kwargs"
1297    /// "#;
1298    ///
1299    /// # fn main() -> PyResult<()> {
1300    /// Python::with_gil(|py| {
1301    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
1302    ///     let fun = module.getattr("function")?;
1303    ///     let args = ("hello",);
1304    ///     let kwargs = PyDict::new_bound(py);
1305    ///     kwargs.set_item("cruel", "world")?;
1306    ///     let result = fun.call(args, Some(&kwargs))?;
1307    ///     assert_eq!(result.extract::<String>()?, "called with args and kwargs");
1308    ///     Ok(())
1309    /// })
1310    /// # }
1311    /// ```
1312    fn call<A>(&self, args: A, kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<Bound<'py, PyAny>>
1313    where
1314        A: IntoPy<Py<PyTuple>>;
1315
1316    /// Calls the object without arguments.
1317    ///
1318    /// This is equivalent to the Python expression `self()`.
1319    ///
1320    /// # Examples
1321    ///
1322    /// ```no_run
1323    /// use pyo3::prelude::*;
1324    ///
1325    /// # fn main() -> PyResult<()> {
1326    /// Python::with_gil(|py| -> PyResult<()> {
1327    ///     let module = PyModule::import_bound(py, "builtins")?;
1328    ///     let help = module.getattr("help")?;
1329    ///     help.call0()?;
1330    ///     Ok(())
1331    /// })?;
1332    /// # Ok(())}
1333    /// ```
1334    ///
1335    /// This is equivalent to the Python expression `help()`.
1336    fn call0(&self) -> PyResult<Bound<'py, PyAny>>;
1337
1338    /// Calls the object with only positional arguments.
1339    ///
1340    /// This is equivalent to the Python expression `self(*args)`.
1341    ///
1342    /// # Examples
1343    ///
1344    /// ```rust
1345    /// use pyo3::prelude::*;
1346    ///
1347    /// const CODE: &str = r#"
1348    /// def function(*args, **kwargs):
1349    ///     assert args == ("hello",)
1350    ///     assert kwargs == {}
1351    ///     return "called with args"
1352    /// "#;
1353    ///
1354    /// # fn main() -> PyResult<()> {
1355    /// Python::with_gil(|py| {
1356    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
1357    ///     let fun = module.getattr("function")?;
1358    ///     let args = ("hello",);
1359    ///     let result = fun.call1(args)?;
1360    ///     assert_eq!(result.extract::<String>()?, "called with args");
1361    ///     Ok(())
1362    /// })
1363    /// # }
1364    /// ```
1365    fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>>
1366    where
1367        A: IntoPy<Py<PyTuple>>;
1368
1369    /// Calls a method on the object.
1370    ///
1371    /// This is equivalent to the Python expression `self.name(*args, **kwargs)`.
1372    ///
1373    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
1374    /// to intern `name`.
1375    ///
1376    /// # Examples
1377    ///
1378    /// ```rust
1379    /// use pyo3::prelude::*;
1380    /// use pyo3::types::PyDict;
1381    ///
1382    /// const CODE: &str = r#"
1383    /// class A:
1384    ///     def method(self, *args, **kwargs):
1385    ///         assert args == ("hello",)
1386    ///         assert kwargs == {"cruel": "world"}
1387    ///         return "called with args and kwargs"
1388    /// a = A()
1389    /// "#;
1390    ///
1391    /// # fn main() -> PyResult<()> {
1392    /// Python::with_gil(|py| {
1393    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
1394    ///     let instance = module.getattr("a")?;
1395    ///     let args = ("hello",);
1396    ///     let kwargs = PyDict::new_bound(py);
1397    ///     kwargs.set_item("cruel", "world")?;
1398    ///     let result = instance.call_method("method", args, Some(&kwargs))?;
1399    ///     assert_eq!(result.extract::<String>()?, "called with args and kwargs");
1400    ///     Ok(())
1401    /// })
1402    /// # }
1403    /// ```
1404    fn call_method<N, A>(
1405        &self,
1406        name: N,
1407        args: A,
1408        kwargs: Option<&Bound<'_, PyDict>>,
1409    ) -> PyResult<Bound<'py, PyAny>>
1410    where
1411        N: IntoPy<Py<PyString>>,
1412        A: IntoPy<Py<PyTuple>>;
1413
1414    /// Calls a method on the object without arguments.
1415    ///
1416    /// This is equivalent to the Python expression `self.name()`.
1417    ///
1418    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
1419    /// to intern `name`.
1420    ///
1421    /// # Examples
1422    ///
1423    /// ```rust
1424    /// use pyo3::prelude::*;
1425    ///
1426    /// const CODE: &str = r#"
1427    /// class A:
1428    ///     def method(self, *args, **kwargs):
1429    ///         assert args == ()
1430    ///         assert kwargs == {}
1431    ///         return "called with no arguments"
1432    /// a = A()
1433    /// "#;
1434    ///
1435    /// # fn main() -> PyResult<()> {
1436    /// Python::with_gil(|py| {
1437    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
1438    ///     let instance = module.getattr("a")?;
1439    ///     let result = instance.call_method0("method")?;
1440    ///     assert_eq!(result.extract::<String>()?, "called with no arguments");
1441    ///     Ok(())
1442    /// })
1443    /// # }
1444    /// ```
1445    fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
1446    where
1447        N: IntoPy<Py<PyString>>;
1448
1449    /// Calls a method on the object with only positional arguments.
1450    ///
1451    /// This is equivalent to the Python expression `self.name(*args)`.
1452    ///
1453    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
1454    /// to intern `name`.
1455    ///
1456    /// # Examples
1457    ///
1458    /// ```rust
1459    /// use pyo3::prelude::*;
1460    ///
1461    /// const CODE: &str = r#"
1462    /// class A:
1463    ///     def method(self, *args, **kwargs):
1464    ///         assert args == ("hello",)
1465    ///         assert kwargs == {}
1466    ///         return "called with args"
1467    /// a = A()
1468    /// "#;
1469    ///
1470    /// # fn main() -> PyResult<()> {
1471    /// Python::with_gil(|py| {
1472    ///     let module = PyModule::from_code_bound(py, CODE, "", "")?;
1473    ///     let instance = module.getattr("a")?;
1474    ///     let args = ("hello",);
1475    ///     let result = instance.call_method1("method", args)?;
1476    ///     assert_eq!(result.extract::<String>()?, "called with args");
1477    ///     Ok(())
1478    /// })
1479    /// # }
1480    /// ```
1481    fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>>
1482    where
1483        N: IntoPy<Py<PyString>>,
1484        A: IntoPy<Py<PyTuple>>;
1485
1486    /// Returns whether the object is considered to be true.
1487    ///
1488    /// This is equivalent to the Python expression `bool(self)`.
1489    fn is_truthy(&self) -> PyResult<bool>;
1490
1491    /// Returns whether the object is considered to be None.
1492    ///
1493    /// This is equivalent to the Python expression `self is None`.
1494    fn is_none(&self) -> bool;
1495
1496    /// Returns whether the object is Ellipsis, e.g. `...`.
1497    ///
1498    /// This is equivalent to the Python expression `self is ...`.
1499    fn is_ellipsis(&self) -> bool;
1500
1501    /// Returns true if the sequence or mapping has a length of 0.
1502    ///
1503    /// This is equivalent to the Python expression `len(self) == 0`.
1504    fn is_empty(&self) -> PyResult<bool>;
1505
1506    /// Gets an item from the collection.
1507    ///
1508    /// This is equivalent to the Python expression `self[key]`.
1509    fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>
1510    where
1511        K: ToPyObject;
1512
1513    /// Sets a collection item value.
1514    ///
1515    /// This is equivalent to the Python expression `self[key] = value`.
1516    fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
1517    where
1518        K: ToPyObject,
1519        V: ToPyObject;
1520
1521    /// Deletes an item from the collection.
1522    ///
1523    /// This is equivalent to the Python expression `del self[key]`.
1524    fn del_item<K>(&self, key: K) -> PyResult<()>
1525    where
1526        K: ToPyObject;
1527
1528    /// Takes an object and returns an iterator for it.
1529    ///
1530    /// This is typically a new iterator but if the argument is an iterator,
1531    /// this returns itself.
1532    fn iter(&self) -> PyResult<Bound<'py, PyIterator>>;
1533
1534    /// Returns the Python type object for this object's type.
1535    fn get_type(&self) -> Bound<'py, PyType>;
1536
1537    /// Returns the Python type pointer for this object.
1538    fn get_type_ptr(&self) -> *mut ffi::PyTypeObject;
1539
1540    /// Downcast this `PyAny` to a concrete Python type or pyclass.
1541    ///
1542    /// Note that you can often avoid downcasting yourself by just specifying
1543    /// the desired type in function or method signatures.
1544    /// However, manual downcasting is sometimes necessary.
1545    ///
1546    /// For extracting a Rust-only type, see [`PyAny::extract`](struct.PyAny.html#method.extract).
1547    ///
1548    /// # Example: Downcasting to a specific Python object
1549    ///
1550    /// ```rust
1551    /// use pyo3::prelude::*;
1552    /// use pyo3::types::{PyDict, PyList};
1553    ///
1554    /// Python::with_gil(|py| {
1555    ///     let dict = PyDict::new_bound(py);
1556    ///     assert!(dict.is_instance_of::<PyAny>());
1557    ///     let any = dict.as_any();
1558    ///
1559    ///     assert!(any.downcast::<PyDict>().is_ok());
1560    ///     assert!(any.downcast::<PyList>().is_err());
1561    /// });
1562    /// ```
1563    ///
1564    /// # Example: Getting a reference to a pyclass
1565    ///
1566    /// This is useful if you want to mutate a `PyObject` that
1567    /// might actually be a pyclass.
1568    ///
1569    /// ```rust
1570    /// # fn main() -> Result<(), pyo3::PyErr> {
1571    /// use pyo3::prelude::*;
1572    ///
1573    /// #[pyclass]
1574    /// struct Class {
1575    ///     i: i32,
1576    /// }
1577    ///
1578    /// Python::with_gil(|py| {
1579    ///     let class = Py::new(py, Class { i: 0 }).unwrap().into_bound(py).into_any();
1580    ///
1581    ///     let class_bound: &Bound<'_, Class> = class.downcast()?;
1582    ///
1583    ///     class_bound.borrow_mut().i += 1;
1584    ///
1585    ///     // Alternatively you can get a `PyRefMut` directly
1586    ///     let class_ref: PyRefMut<'_, Class> = class.extract()?;
1587    ///     assert_eq!(class_ref.i, 1);
1588    ///     Ok(())
1589    /// })
1590    /// # }
1591    /// ```
1592    fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
1593    where
1594        T: PyTypeCheck;
1595
1596    /// Like `downcast` but takes ownership of `self`.
1597    ///
1598    /// In case of an error, it is possible to retrieve `self` again via [`DowncastIntoError::into_inner`].
1599    ///
1600    /// # Example
1601    ///
1602    /// ```rust
1603    /// use pyo3::prelude::*;
1604    /// use pyo3::types::{PyDict, PyList};
1605    ///
1606    /// Python::with_gil(|py| {
1607    ///     let obj: Bound<'_, PyAny> = PyDict::new_bound(py).into_any();
1608    ///
1609    ///     let obj: Bound<'_, PyAny> = match obj.downcast_into::<PyList>() {
1610    ///         Ok(_) => panic!("obj should not be a list"),
1611    ///         Err(err) => err.into_inner(),
1612    ///     };
1613    ///
1614    ///     // obj is a dictionary
1615    ///     assert!(obj.downcast_into::<PyDict>().is_ok());
1616    /// })
1617    /// ```
1618    fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>>
1619    where
1620        T: PyTypeCheck;
1621
1622    /// Downcast this `PyAny` to a concrete Python type or pyclass (but not a subclass of it).
1623    ///
1624    /// It is almost always better to use [`PyAnyMethods::downcast`] because it accounts for Python
1625    /// subtyping. Use this method only when you do not want to allow subtypes.
1626    ///
1627    /// The advantage of this method over [`PyAnyMethods::downcast`] is that it is faster. The implementation
1628    /// of `downcast_exact` uses the equivalent of the Python expression `type(self) is T`, whereas
1629    /// `downcast` uses `isinstance(self, T)`.
1630    ///
1631    /// For extracting a Rust-only type, see [`PyAny::extract`](struct.PyAny.html#method.extract).
1632    ///
1633    /// # Example: Downcasting to a specific Python object but not a subtype
1634    ///
1635    /// ```rust
1636    /// use pyo3::prelude::*;
1637    /// use pyo3::types::{PyBool, PyLong};
1638    ///
1639    /// Python::with_gil(|py| {
1640    ///     let b = PyBool::new_bound(py, true);
1641    ///     assert!(b.is_instance_of::<PyBool>());
1642    ///     let any: &Bound<'_, PyAny> = b.as_any();
1643    ///
1644    ///     // `bool` is a subtype of `int`, so `downcast` will accept a `bool` as an `int`
1645    ///     // but `downcast_exact` will not.
1646    ///     assert!(any.downcast::<PyLong>().is_ok());
1647    ///     assert!(any.downcast_exact::<PyLong>().is_err());
1648    ///
1649    ///     assert!(any.downcast_exact::<PyBool>().is_ok());
1650    /// });
1651    /// ```
1652    fn downcast_exact<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
1653    where
1654        T: PyTypeInfo;
1655
1656    /// Like `downcast_exact` but takes ownership of `self`.
1657    fn downcast_into_exact<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>>
1658    where
1659        T: PyTypeInfo;
1660
1661    /// Converts this `PyAny` to a concrete Python type without checking validity.
1662    ///
1663    /// # Safety
1664    ///
1665    /// Callers must ensure that the type is valid or risk type confusion.
1666    unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T>;
1667
1668    /// Like `downcast_unchecked` but takes ownership of `self`.
1669    ///
1670    /// # Safety
1671    ///
1672    /// Callers must ensure that the type is valid or risk type confusion.
1673    unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T>;
1674
1675    /// Extracts some type from the Python object.
1676    ///
1677    /// This is a wrapper function around
1678    /// [`FromPyObject::extract_bound()`](crate::FromPyObject::extract_bound).
1679    fn extract<'a, T>(&'a self) -> PyResult<T>
1680    where
1681        T: FromPyObjectBound<'a, 'py>;
1682
1683    /// Returns the reference count for the Python object.
1684    fn get_refcnt(&self) -> isize;
1685
1686    /// Computes the "repr" representation of self.
1687    ///
1688    /// This is equivalent to the Python expression `repr(self)`.
1689    fn repr(&self) -> PyResult<Bound<'py, PyString>>;
1690
1691    /// Computes the "str" representation of self.
1692    ///
1693    /// This is equivalent to the Python expression `str(self)`.
1694    fn str(&self) -> PyResult<Bound<'py, PyString>>;
1695
1696    /// Retrieves the hash code of self.
1697    ///
1698    /// This is equivalent to the Python expression `hash(self)`.
1699    fn hash(&self) -> PyResult<isize>;
1700
1701    /// Returns the length of the sequence or mapping.
1702    ///
1703    /// This is equivalent to the Python expression `len(self)`.
1704    fn len(&self) -> PyResult<usize>;
1705
1706    /// Returns the list of attributes of this object.
1707    ///
1708    /// This is equivalent to the Python expression `dir(self)`.
1709    fn dir(&self) -> PyResult<Bound<'py, PyList>>;
1710
1711    /// Checks whether this object is an instance of type `ty`.
1712    ///
1713    /// This is equivalent to the Python expression `isinstance(self, ty)`.
1714    fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>;
1715
1716    /// Checks whether this object is an instance of exactly type `ty` (not a subclass).
1717    ///
1718    /// This is equivalent to the Python expression `type(self) is ty`.
1719    fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool;
1720
1721    /// Checks whether this object is an instance of type `T`.
1722    ///
1723    /// This is equivalent to the Python expression `isinstance(self, T)`,
1724    /// if the type `T` is known at compile time.
1725    fn is_instance_of<T: PyTypeInfo>(&self) -> bool;
1726
1727    /// Checks whether this object is an instance of exactly type `T`.
1728    ///
1729    /// This is equivalent to the Python expression `type(self) is T`,
1730    /// if the type `T` is known at compile time.
1731    fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool;
1732
1733    /// Determines if self contains `value`.
1734    ///
1735    /// This is equivalent to the Python expression `value in self`.
1736    fn contains<V>(&self, value: V) -> PyResult<bool>
1737    where
1738        V: ToPyObject;
1739
1740    /// Return a proxy object that delegates method calls to a parent or sibling class of type.
1741    ///
1742    /// This is equivalent to the Python expression `super()`
1743    #[cfg(not(any(PyPy, GraalPy)))]
1744    fn py_super(&self) -> PyResult<Bound<'py, PySuper>>;
1745}
1746
1747macro_rules! implement_binop {
1748    ($name:ident, $c_api:ident, $op:expr) => {
1749        #[doc = concat!("Computes `self ", $op, " other`.")]
1750        fn $name<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1751        where
1752            O: ToPyObject,
1753        {
1754            fn inner<'py>(
1755                any: &Bound<'py, PyAny>,
1756                other: Bound<'_, PyAny>,
1757            ) -> PyResult<Bound<'py, PyAny>> {
1758                unsafe { ffi::$c_api(any.as_ptr(), other.as_ptr()).assume_owned_or_err(any.py()) }
1759            }
1760
1761            let py = self.py();
1762            inner(self, other.to_object(py).into_bound(py))
1763        }
1764    };
1765}
1766
1767impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
1768    #[inline]
1769    fn is<T: AsPyPointer>(&self, other: &T) -> bool {
1770        self.as_ptr() == other.as_ptr()
1771    }
1772
1773    fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
1774    where
1775        N: IntoPy<Py<PyString>>,
1776    {
1777        // PyObject_HasAttr suppresses all exceptions, which was the behaviour of `hasattr` in Python 2.
1778        // Use an implementation which suppresses only AttributeError, which is consistent with `hasattr` in Python 3.
1779        fn inner(py: Python<'_>, getattr_result: PyResult<Bound<'_, PyAny>>) -> PyResult<bool> {
1780            match getattr_result {
1781                Ok(_) => Ok(true),
1782                Err(err) if err.is_instance_of::<PyAttributeError>(py) => Ok(false),
1783                Err(e) => Err(e),
1784            }
1785        }
1786
1787        inner(self.py(), self.getattr(attr_name))
1788    }
1789
1790    fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
1791    where
1792        N: IntoPy<Py<PyString>>,
1793    {
1794        fn inner<'py>(
1795            any: &Bound<'py, PyAny>,
1796            attr_name: Bound<'_, PyString>,
1797        ) -> PyResult<Bound<'py, PyAny>> {
1798            unsafe {
1799                ffi::PyObject_GetAttr(any.as_ptr(), attr_name.as_ptr())
1800                    .assume_owned_or_err(any.py())
1801            }
1802        }
1803
1804        let py = self.py();
1805        inner(self, attr_name.into_py(self.py()).into_bound(py))
1806    }
1807
1808    fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
1809    where
1810        N: IntoPy<Py<PyString>>,
1811        V: ToPyObject,
1812    {
1813        fn inner(
1814            any: &Bound<'_, PyAny>,
1815            attr_name: Bound<'_, PyString>,
1816            value: Bound<'_, PyAny>,
1817        ) -> PyResult<()> {
1818            err::error_on_minusone(any.py(), unsafe {
1819                ffi::PyObject_SetAttr(any.as_ptr(), attr_name.as_ptr(), value.as_ptr())
1820            })
1821        }
1822
1823        let py = self.py();
1824        inner(
1825            self,
1826            attr_name.into_py(py).into_bound(py),
1827            value.to_object(py).into_bound(py),
1828        )
1829    }
1830
1831    fn delattr<N>(&self, attr_name: N) -> PyResult<()>
1832    where
1833        N: IntoPy<Py<PyString>>,
1834    {
1835        fn inner(any: &Bound<'_, PyAny>, attr_name: Bound<'_, PyString>) -> PyResult<()> {
1836            err::error_on_minusone(any.py(), unsafe {
1837                ffi::PyObject_DelAttr(any.as_ptr(), attr_name.as_ptr())
1838            })
1839        }
1840
1841        let py = self.py();
1842        inner(self, attr_name.into_py(py).into_bound(py))
1843    }
1844
1845    fn compare<O>(&self, other: O) -> PyResult<Ordering>
1846    where
1847        O: ToPyObject,
1848    {
1849        fn inner(any: &Bound<'_, PyAny>, other: Bound<'_, PyAny>) -> PyResult<Ordering> {
1850            let other = other.as_ptr();
1851            // Almost the same as ffi::PyObject_RichCompareBool, but this one doesn't try self == other.
1852            // See https://github.com/PyO3/pyo3/issues/985 for more.
1853            let do_compare = |other, op| unsafe {
1854                ffi::PyObject_RichCompare(any.as_ptr(), other, op)
1855                    .assume_owned_or_err(any.py())
1856                    .and_then(|obj| obj.is_truthy())
1857            };
1858            if do_compare(other, ffi::Py_EQ)? {
1859                Ok(Ordering::Equal)
1860            } else if do_compare(other, ffi::Py_LT)? {
1861                Ok(Ordering::Less)
1862            } else if do_compare(other, ffi::Py_GT)? {
1863                Ok(Ordering::Greater)
1864            } else {
1865                Err(PyTypeError::new_err(
1866                    "PyAny::compare(): All comparisons returned false",
1867                ))
1868            }
1869        }
1870
1871        let py = self.py();
1872        inner(self, other.to_object(py).into_bound(py))
1873    }
1874
1875    fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>>
1876    where
1877        O: ToPyObject,
1878    {
1879        fn inner<'py>(
1880            any: &Bound<'py, PyAny>,
1881            other: Bound<'_, PyAny>,
1882            compare_op: CompareOp,
1883        ) -> PyResult<Bound<'py, PyAny>> {
1884            unsafe {
1885                ffi::PyObject_RichCompare(any.as_ptr(), other.as_ptr(), compare_op as c_int)
1886                    .assume_owned_or_err(any.py())
1887            }
1888        }
1889
1890        let py = self.py();
1891        inner(self, other.to_object(py).into_bound(py), compare_op)
1892    }
1893
1894    fn neg(&self) -> PyResult<Bound<'py, PyAny>> {
1895        unsafe { ffi::PyNumber_Negative(self.as_ptr()).assume_owned_or_err(self.py()) }
1896    }
1897
1898    fn pos(&self) -> PyResult<Bound<'py, PyAny>> {
1899        fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
1900            unsafe { ffi::PyNumber_Positive(any.as_ptr()).assume_owned_or_err(any.py()) }
1901        }
1902
1903        inner(self)
1904    }
1905
1906    fn abs(&self) -> PyResult<Bound<'py, PyAny>> {
1907        fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
1908            unsafe { ffi::PyNumber_Absolute(any.as_ptr()).assume_owned_or_err(any.py()) }
1909        }
1910
1911        inner(self)
1912    }
1913
1914    fn bitnot(&self) -> PyResult<Bound<'py, PyAny>> {
1915        fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
1916            unsafe { ffi::PyNumber_Invert(any.as_ptr()).assume_owned_or_err(any.py()) }
1917        }
1918
1919        inner(self)
1920    }
1921
1922    fn lt<O>(&self, other: O) -> PyResult<bool>
1923    where
1924        O: ToPyObject,
1925    {
1926        self.rich_compare(other, CompareOp::Lt)
1927            .and_then(|any| any.is_truthy())
1928    }
1929
1930    fn le<O>(&self, other: O) -> PyResult<bool>
1931    where
1932        O: ToPyObject,
1933    {
1934        self.rich_compare(other, CompareOp::Le)
1935            .and_then(|any| any.is_truthy())
1936    }
1937
1938    fn eq<O>(&self, other: O) -> PyResult<bool>
1939    where
1940        O: ToPyObject,
1941    {
1942        self.rich_compare(other, CompareOp::Eq)
1943            .and_then(|any| any.is_truthy())
1944    }
1945
1946    fn ne<O>(&self, other: O) -> PyResult<bool>
1947    where
1948        O: ToPyObject,
1949    {
1950        self.rich_compare(other, CompareOp::Ne)
1951            .and_then(|any| any.is_truthy())
1952    }
1953
1954    fn gt<O>(&self, other: O) -> PyResult<bool>
1955    where
1956        O: ToPyObject,
1957    {
1958        self.rich_compare(other, CompareOp::Gt)
1959            .and_then(|any| any.is_truthy())
1960    }
1961
1962    fn ge<O>(&self, other: O) -> PyResult<bool>
1963    where
1964        O: ToPyObject,
1965    {
1966        self.rich_compare(other, CompareOp::Ge)
1967            .and_then(|any| any.is_truthy())
1968    }
1969
1970    implement_binop!(add, PyNumber_Add, "+");
1971    implement_binop!(sub, PyNumber_Subtract, "-");
1972    implement_binop!(mul, PyNumber_Multiply, "*");
1973    implement_binop!(matmul, PyNumber_MatrixMultiply, "@");
1974    implement_binop!(div, PyNumber_TrueDivide, "/");
1975    implement_binop!(floor_div, PyNumber_FloorDivide, "//");
1976    implement_binop!(rem, PyNumber_Remainder, "%");
1977    implement_binop!(lshift, PyNumber_Lshift, "<<");
1978    implement_binop!(rshift, PyNumber_Rshift, ">>");
1979    implement_binop!(bitand, PyNumber_And, "&");
1980    implement_binop!(bitor, PyNumber_Or, "|");
1981    implement_binop!(bitxor, PyNumber_Xor, "^");
1982
1983    /// Computes `divmod(self, other)`.
1984    fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1985    where
1986        O: ToPyObject,
1987    {
1988        fn inner<'py>(
1989            any: &Bound<'py, PyAny>,
1990            other: Bound<'_, PyAny>,
1991        ) -> PyResult<Bound<'py, PyAny>> {
1992            unsafe {
1993                ffi::PyNumber_Divmod(any.as_ptr(), other.as_ptr()).assume_owned_or_err(any.py())
1994            }
1995        }
1996
1997        let py = self.py();
1998        inner(self, other.to_object(py).into_bound(py))
1999    }
2000
2001    /// Computes `self ** other % modulus` (`pow(self, other, modulus)`).
2002    /// `py.None()` may be passed for the `modulus`.
2003    fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>
2004    where
2005        O1: ToPyObject,
2006        O2: ToPyObject,
2007    {
2008        fn inner<'py>(
2009            any: &Bound<'py, PyAny>,
2010            other: Bound<'_, PyAny>,
2011            modulus: Bound<'_, PyAny>,
2012        ) -> PyResult<Bound<'py, PyAny>> {
2013            unsafe {
2014                ffi::PyNumber_Power(any.as_ptr(), other.as_ptr(), modulus.as_ptr())
2015                    .assume_owned_or_err(any.py())
2016            }
2017        }
2018
2019        let py = self.py();
2020        inner(
2021            self,
2022            other.to_object(py).into_bound(py),
2023            modulus.to_object(py).into_bound(py),
2024        )
2025    }
2026
2027    fn is_callable(&self) -> bool {
2028        unsafe { ffi::PyCallable_Check(self.as_ptr()) != 0 }
2029    }
2030
2031    fn call<A>(&self, args: A, kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<Bound<'py, PyAny>>
2032    where
2033        A: IntoPy<Py<PyTuple>>,
2034    {
2035        args.__py_call_vectorcall(
2036            self.py(),
2037            self.as_borrowed(),
2038            kwargs.map(Bound::as_borrowed),
2039            private::Token,
2040        )
2041    }
2042
2043    #[inline]
2044    fn call0(&self) -> PyResult<Bound<'py, PyAny>> {
2045        unsafe { ffi::compat::PyObject_CallNoArgs(self.as_ptr()).assume_owned_or_err(self.py()) }
2046    }
2047
2048    fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>>
2049    where
2050        A: IntoPy<Py<PyTuple>>,
2051    {
2052        args.__py_call_vectorcall1(self.py(), self.as_borrowed(), private::Token)
2053    }
2054
2055    #[inline]
2056    fn call_method<N, A>(
2057        &self,
2058        name: N,
2059        args: A,
2060        kwargs: Option<&Bound<'_, PyDict>>,
2061    ) -> PyResult<Bound<'py, PyAny>>
2062    where
2063        N: IntoPy<Py<PyString>>,
2064        A: IntoPy<Py<PyTuple>>,
2065    {
2066        // Don't `args.into_py()`! This will lose the optimization of vectorcall.
2067        match kwargs {
2068            Some(_) => self
2069                .getattr(name)
2070                .and_then(|method| method.call(args, kwargs)),
2071            None => self.call_method1(name, args),
2072        }
2073    }
2074
2075    #[inline]
2076    fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
2077    where
2078        N: IntoPy<Py<PyString>>,
2079    {
2080        let py = self.py();
2081        let name = name.into_py(py).into_bound(py);
2082        unsafe {
2083            ffi::compat::PyObject_CallMethodNoArgs(self.as_ptr(), name.as_ptr())
2084                .assume_owned_or_err(py)
2085        }
2086    }
2087
2088    fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>>
2089    where
2090        N: IntoPy<Py<PyString>>,
2091        A: IntoPy<Py<PyTuple>>,
2092    {
2093        args.__py_call_method_vectorcall1(
2094            self.py(),
2095            self.as_borrowed(),
2096            name.into_py(self.py()).bind_borrowed(self.py()),
2097            private::Token,
2098        )
2099    }
2100
2101    fn is_truthy(&self) -> PyResult<bool> {
2102        let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) };
2103        err::error_on_minusone(self.py(), v)?;
2104        Ok(v != 0)
2105    }
2106
2107    #[inline]
2108    fn is_none(&self) -> bool {
2109        unsafe { ffi::Py_None() == self.as_ptr() }
2110    }
2111
2112    fn is_ellipsis(&self) -> bool {
2113        unsafe { ffi::Py_Ellipsis() == self.as_ptr() }
2114    }
2115
2116    fn is_empty(&self) -> PyResult<bool> {
2117        self.len().map(|l| l == 0)
2118    }
2119
2120    fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>
2121    where
2122        K: ToPyObject,
2123    {
2124        fn inner<'py>(
2125            any: &Bound<'py, PyAny>,
2126            key: Bound<'_, PyAny>,
2127        ) -> PyResult<Bound<'py, PyAny>> {
2128            unsafe {
2129                ffi::PyObject_GetItem(any.as_ptr(), key.as_ptr()).assume_owned_or_err(any.py())
2130            }
2131        }
2132
2133        let py = self.py();
2134        inner(self, key.to_object(py).into_bound(py))
2135    }
2136
2137    fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
2138    where
2139        K: ToPyObject,
2140        V: ToPyObject,
2141    {
2142        fn inner(
2143            any: &Bound<'_, PyAny>,
2144            key: Bound<'_, PyAny>,
2145            value: Bound<'_, PyAny>,
2146        ) -> PyResult<()> {
2147            err::error_on_minusone(any.py(), unsafe {
2148                ffi::PyObject_SetItem(any.as_ptr(), key.as_ptr(), value.as_ptr())
2149            })
2150        }
2151
2152        let py = self.py();
2153        inner(
2154            self,
2155            key.to_object(py).into_bound(py),
2156            value.to_object(py).into_bound(py),
2157        )
2158    }
2159
2160    fn del_item<K>(&self, key: K) -> PyResult<()>
2161    where
2162        K: ToPyObject,
2163    {
2164        fn inner(any: &Bound<'_, PyAny>, key: Bound<'_, PyAny>) -> PyResult<()> {
2165            err::error_on_minusone(any.py(), unsafe {
2166                ffi::PyObject_DelItem(any.as_ptr(), key.as_ptr())
2167            })
2168        }
2169
2170        let py = self.py();
2171        inner(self, key.to_object(py).into_bound(py))
2172    }
2173
2174    fn iter(&self) -> PyResult<Bound<'py, PyIterator>> {
2175        PyIterator::from_bound_object(self)
2176    }
2177
2178    fn get_type(&self) -> Bound<'py, PyType> {
2179        unsafe { PyType::from_borrowed_type_ptr(self.py(), ffi::Py_TYPE(self.as_ptr())) }
2180    }
2181
2182    #[inline]
2183    fn get_type_ptr(&self) -> *mut ffi::PyTypeObject {
2184        unsafe { ffi::Py_TYPE(self.as_ptr()) }
2185    }
2186
2187    #[inline]
2188    fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
2189    where
2190        T: PyTypeCheck,
2191    {
2192        if T::type_check(self) {
2193            // Safety: type_check is responsible for ensuring that the type is correct
2194            Ok(unsafe { self.downcast_unchecked() })
2195        } else {
2196            Err(DowncastError::new(self, T::NAME))
2197        }
2198    }
2199
2200    #[inline]
2201    fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>>
2202    where
2203        T: PyTypeCheck,
2204    {
2205        if T::type_check(&self) {
2206            // Safety: type_check is responsible for ensuring that the type is correct
2207            Ok(unsafe { self.downcast_into_unchecked() })
2208        } else {
2209            Err(DowncastIntoError::new(self, T::NAME))
2210        }
2211    }
2212
2213    #[inline]
2214    fn downcast_exact<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
2215    where
2216        T: PyTypeInfo,
2217    {
2218        if self.is_exact_instance_of::<T>() {
2219            // Safety: is_exact_instance_of is responsible for ensuring that the type is correct
2220            Ok(unsafe { self.downcast_unchecked() })
2221        } else {
2222            Err(DowncastError::new(self, T::NAME))
2223        }
2224    }
2225
2226    #[inline]
2227    fn downcast_into_exact<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>>
2228    where
2229        T: PyTypeInfo,
2230    {
2231        if self.is_exact_instance_of::<T>() {
2232            // Safety: is_exact_instance_of is responsible for ensuring that the type is correct
2233            Ok(unsafe { self.downcast_into_unchecked() })
2234        } else {
2235            Err(DowncastIntoError::new(self, T::NAME))
2236        }
2237    }
2238
2239    #[inline]
2240    unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T> {
2241        &*ptr_from_ref(self).cast()
2242    }
2243
2244    #[inline]
2245    unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T> {
2246        std::mem::transmute(self)
2247    }
2248
2249    fn extract<'a, T>(&'a self) -> PyResult<T>
2250    where
2251        T: FromPyObjectBound<'a, 'py>,
2252    {
2253        FromPyObjectBound::from_py_object_bound(self.as_borrowed())
2254    }
2255
2256    fn get_refcnt(&self) -> isize {
2257        unsafe { ffi::Py_REFCNT(self.as_ptr()) }
2258    }
2259
2260    fn repr(&self) -> PyResult<Bound<'py, PyString>> {
2261        unsafe {
2262            ffi::PyObject_Repr(self.as_ptr())
2263                .assume_owned_or_err(self.py())
2264                .downcast_into_unchecked()
2265        }
2266    }
2267
2268    fn str(&self) -> PyResult<Bound<'py, PyString>> {
2269        unsafe {
2270            ffi::PyObject_Str(self.as_ptr())
2271                .assume_owned_or_err(self.py())
2272                .downcast_into_unchecked()
2273        }
2274    }
2275
2276    fn hash(&self) -> PyResult<isize> {
2277        let v = unsafe { ffi::PyObject_Hash(self.as_ptr()) };
2278        crate::err::error_on_minusone(self.py(), v)?;
2279        Ok(v)
2280    }
2281
2282    fn len(&self) -> PyResult<usize> {
2283        let v = unsafe { ffi::PyObject_Size(self.as_ptr()) };
2284        crate::err::error_on_minusone(self.py(), v)?;
2285        Ok(v as usize)
2286    }
2287
2288    fn dir(&self) -> PyResult<Bound<'py, PyList>> {
2289        unsafe {
2290            ffi::PyObject_Dir(self.as_ptr())
2291                .assume_owned_or_err(self.py())
2292                .downcast_into_unchecked()
2293        }
2294    }
2295
2296    #[inline]
2297    fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool> {
2298        let result = unsafe { ffi::PyObject_IsInstance(self.as_ptr(), ty.as_ptr()) };
2299        err::error_on_minusone(self.py(), result)?;
2300        Ok(result == 1)
2301    }
2302
2303    #[inline]
2304    fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool {
2305        self.get_type().is(ty)
2306    }
2307
2308    #[inline]
2309    fn is_instance_of<T: PyTypeInfo>(&self) -> bool {
2310        T::is_type_of_bound(self)
2311    }
2312
2313    #[inline]
2314    fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool {
2315        T::is_exact_type_of_bound(self)
2316    }
2317
2318    fn contains<V>(&self, value: V) -> PyResult<bool>
2319    where
2320        V: ToPyObject,
2321    {
2322        fn inner(any: &Bound<'_, PyAny>, value: Bound<'_, PyAny>) -> PyResult<bool> {
2323            match unsafe { ffi::PySequence_Contains(any.as_ptr(), value.as_ptr()) } {
2324                0 => Ok(false),
2325                1 => Ok(true),
2326                _ => Err(PyErr::fetch(any.py())),
2327            }
2328        }
2329
2330        let py = self.py();
2331        inner(self, value.to_object(py).into_bound(py))
2332    }
2333
2334    #[cfg(not(any(PyPy, GraalPy)))]
2335    fn py_super(&self) -> PyResult<Bound<'py, PySuper>> {
2336        PySuper::new_bound(&self.get_type(), self)
2337    }
2338}
2339
2340impl<'py> Bound<'py, PyAny> {
2341    /// Retrieve an attribute value, skipping the instance dictionary during the lookup but still
2342    /// binding the object to the instance.
2343    ///
2344    /// This is useful when trying to resolve Python's "magic" methods like `__getitem__`, which
2345    /// are looked up starting from the type object.  This returns an `Option` as it is not
2346    /// typically a direct error for the special lookup to fail, as magic methods are optional in
2347    /// many situations in which they might be called.
2348    ///
2349    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
2350    /// to intern `attr_name`.
2351    #[allow(dead_code)] // Currently only used with num-complex+abi3, so dead without that.
2352    pub(crate) fn lookup_special<N>(&self, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>
2353    where
2354        N: IntoPy<Py<PyString>>,
2355    {
2356        let py = self.py();
2357        let self_type = self.get_type();
2358        let attr = if let Ok(attr) = self_type.getattr(attr_name) {
2359            attr
2360        } else {
2361            return Ok(None);
2362        };
2363
2364        // Manually resolve descriptor protocol. (Faster than going through Python.)
2365        if let Some(descr_get) = attr.get_type().get_slot(TP_DESCR_GET) {
2366            // attribute is a descriptor, resolve it
2367            unsafe {
2368                descr_get(attr.as_ptr(), self.as_ptr(), self_type.as_ptr())
2369                    .assume_owned_or_err(py)
2370                    .map(Some)
2371            }
2372        } else {
2373            Ok(Some(attr))
2374        }
2375    }
2376}
2377
2378#[cfg(test)]
2379mod tests {
2380    use crate::{
2381        basic::CompareOp,
2382        types::{IntoPyDict, PyAny, PyAnyMethods, PyBool, PyList, PyLong, PyModule, PyTypeMethods},
2383        Bound, PyTypeInfo, Python, ToPyObject,
2384    };
2385
2386    #[test]
2387    fn test_lookup_special() {
2388        Python::with_gil(|py| {
2389            let module = PyModule::from_code_bound(
2390                py,
2391                r#"
2392class CustomCallable:
2393    def __call__(self):
2394        return 1
2395
2396class SimpleInt:
2397    def __int__(self):
2398        return 1
2399
2400class InheritedInt(SimpleInt): pass
2401
2402class NoInt: pass
2403
2404class NoDescriptorInt:
2405    __int__ = CustomCallable()
2406
2407class InstanceOverrideInt:
2408    def __int__(self):
2409        return 1
2410instance_override = InstanceOverrideInt()
2411instance_override.__int__ = lambda self: 2
2412
2413class ErrorInDescriptorInt:
2414    @property
2415    def __int__(self):
2416        raise ValueError("uh-oh!")
2417
2418class NonHeapNonDescriptorInt:
2419    # A static-typed callable that doesn't implement `__get__`.  These are pretty hard to come by.
2420    __int__ = int
2421                "#,
2422                "test.py",
2423                "test",
2424            )
2425            .unwrap();
2426
2427            let int = crate::intern!(py, "__int__");
2428            let eval_int =
2429                |obj: Bound<'_, PyAny>| obj.lookup_special(int)?.unwrap().call0()?.extract::<u32>();
2430
2431            let simple = module.getattr("SimpleInt").unwrap().call0().unwrap();
2432            assert_eq!(eval_int(simple).unwrap(), 1);
2433            let inherited = module.getattr("InheritedInt").unwrap().call0().unwrap();
2434            assert_eq!(eval_int(inherited).unwrap(), 1);
2435            let no_descriptor = module.getattr("NoDescriptorInt").unwrap().call0().unwrap();
2436            assert_eq!(eval_int(no_descriptor).unwrap(), 1);
2437            let missing = module.getattr("NoInt").unwrap().call0().unwrap();
2438            assert!(missing.as_borrowed().lookup_special(int).unwrap().is_none());
2439            // Note the instance override should _not_ call the instance method that returns 2,
2440            // because that's not how special lookups are meant to work.
2441            let instance_override = module.getattr("instance_override").unwrap();
2442            assert_eq!(eval_int(instance_override).unwrap(), 1);
2443            let descriptor_error = module
2444                .getattr("ErrorInDescriptorInt")
2445                .unwrap()
2446                .call0()
2447                .unwrap();
2448            assert!(descriptor_error.as_borrowed().lookup_special(int).is_err());
2449            let nonheap_nondescriptor = module
2450                .getattr("NonHeapNonDescriptorInt")
2451                .unwrap()
2452                .call0()
2453                .unwrap();
2454            assert_eq!(eval_int(nonheap_nondescriptor).unwrap(), 0);
2455        })
2456    }
2457
2458    #[test]
2459    fn test_call_for_non_existing_method() {
2460        Python::with_gil(|py| {
2461            let a = py.eval_bound("42", None, None).unwrap();
2462            a.call_method0("__str__").unwrap(); // ok
2463            assert!(a.call_method("nonexistent_method", (1,), None).is_err());
2464            assert!(a.call_method0("nonexistent_method").is_err());
2465            assert!(a.call_method1("nonexistent_method", (1,)).is_err());
2466        });
2467    }
2468
2469    #[test]
2470    fn test_call_with_kwargs() {
2471        Python::with_gil(|py| {
2472            let list = vec![3, 6, 5, 4, 7].to_object(py);
2473            let dict = vec![("reverse", true)].into_py_dict_bound(py);
2474            list.call_method_bound(py, "sort", (), Some(&dict)).unwrap();
2475            assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]);
2476        });
2477    }
2478
2479    #[test]
2480    fn test_call_method0() {
2481        Python::with_gil(|py| {
2482            let module = PyModule::from_code_bound(
2483                py,
2484                r#"
2485class SimpleClass:
2486    def foo(self):
2487        return 42
2488"#,
2489                file!(),
2490                "test_module",
2491            )
2492            .expect("module creation failed");
2493
2494            let simple_class = module.getattr("SimpleClass").unwrap().call0().unwrap();
2495            assert_eq!(
2496                simple_class
2497                    .call_method0("foo")
2498                    .unwrap()
2499                    .extract::<u32>()
2500                    .unwrap(),
2501                42
2502            );
2503        })
2504    }
2505
2506    #[test]
2507    fn test_type() {
2508        Python::with_gil(|py| {
2509            let obj = py.eval_bound("42", None, None).unwrap();
2510            assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr());
2511        });
2512    }
2513
2514    #[test]
2515    fn test_dir() {
2516        Python::with_gil(|py| {
2517            let obj = py.eval_bound("42", None, None).unwrap();
2518            let dir = py
2519                .eval_bound("dir(42)", None, None)
2520                .unwrap()
2521                .downcast_into::<PyList>()
2522                .unwrap();
2523            let a = obj
2524                .dir()
2525                .unwrap()
2526                .into_iter()
2527                .map(|x| x.extract::<String>().unwrap());
2528            let b = dir.into_iter().map(|x| x.extract::<String>().unwrap());
2529            assert!(a.eq(b));
2530        });
2531    }
2532
2533    #[test]
2534    fn test_hasattr() {
2535        Python::with_gil(|py| {
2536            let x = 5.to_object(py).into_bound(py);
2537            assert!(x.is_instance_of::<PyLong>());
2538
2539            assert!(x.hasattr("to_bytes").unwrap());
2540            assert!(!x.hasattr("bbbbbbytes").unwrap());
2541        })
2542    }
2543
2544    #[cfg(feature = "macros")]
2545    #[test]
2546    #[allow(unknown_lints, non_local_definitions)]
2547    fn test_hasattr_error() {
2548        use crate::exceptions::PyValueError;
2549        use crate::prelude::*;
2550
2551        #[pyclass(crate = "crate")]
2552        struct GetattrFail;
2553
2554        #[pymethods(crate = "crate")]
2555        impl GetattrFail {
2556            fn __getattr__(&self, attr: PyObject) -> PyResult<PyObject> {
2557                Err(PyValueError::new_err(attr))
2558            }
2559        }
2560
2561        Python::with_gil(|py| {
2562            let obj = Py::new(py, GetattrFail).unwrap();
2563            let obj = obj.bind(py).as_ref();
2564
2565            assert!(obj
2566                .hasattr("foo")
2567                .unwrap_err()
2568                .is_instance_of::<PyValueError>(py));
2569        })
2570    }
2571
2572    #[test]
2573    fn test_nan_eq() {
2574        Python::with_gil(|py| {
2575            let nan = py.eval_bound("float('nan')", None, None).unwrap();
2576            assert!(nan.compare(&nan).is_err());
2577        });
2578    }
2579
2580    #[test]
2581    fn test_any_is_instance_of() {
2582        Python::with_gil(|py| {
2583            let x = 5.to_object(py).into_bound(py);
2584            assert!(x.is_instance_of::<PyLong>());
2585
2586            let l = vec![&x, &x].to_object(py).into_bound(py);
2587            assert!(l.is_instance_of::<PyList>());
2588        });
2589    }
2590
2591    #[test]
2592    fn test_any_is_instance() {
2593        Python::with_gil(|py| {
2594            let l = vec![1u8, 2].to_object(py).into_bound(py);
2595            assert!(l.is_instance(&py.get_type_bound::<PyList>()).unwrap());
2596        });
2597    }
2598
2599    #[test]
2600    fn test_any_is_exact_instance_of() {
2601        Python::with_gil(|py| {
2602            let x = 5.to_object(py).into_bound(py);
2603            assert!(x.is_exact_instance_of::<PyLong>());
2604
2605            let t = PyBool::new_bound(py, true);
2606            assert!(t.is_instance_of::<PyLong>());
2607            assert!(!t.is_exact_instance_of::<PyLong>());
2608            assert!(t.is_exact_instance_of::<PyBool>());
2609
2610            let l = vec![&x, &x].to_object(py).into_bound(py);
2611            assert!(l.is_exact_instance_of::<PyList>());
2612        });
2613    }
2614
2615    #[test]
2616    fn test_any_is_exact_instance() {
2617        Python::with_gil(|py| {
2618            let t = PyBool::new_bound(py, true);
2619            assert!(t.is_instance(&py.get_type_bound::<PyLong>()).unwrap());
2620            assert!(!t.is_exact_instance(&py.get_type_bound::<PyLong>()));
2621            assert!(t.is_exact_instance(&py.get_type_bound::<PyBool>()));
2622        });
2623    }
2624
2625    #[test]
2626    fn test_any_contains() {
2627        Python::with_gil(|py| {
2628            let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
2629            let ob = v.to_object(py).into_bound(py);
2630
2631            let bad_needle = 7i32.to_object(py);
2632            assert!(!ob.contains(&bad_needle).unwrap());
2633
2634            let good_needle = 8i32.to_object(py);
2635            assert!(ob.contains(&good_needle).unwrap());
2636
2637            let type_coerced_needle = 8f32.to_object(py);
2638            assert!(ob.contains(&type_coerced_needle).unwrap());
2639
2640            let n: u32 = 42;
2641            let bad_haystack = n.to_object(py).into_bound(py);
2642            let irrelevant_needle = 0i32.to_object(py);
2643            assert!(bad_haystack.contains(&irrelevant_needle).is_err());
2644        });
2645    }
2646
2647    // This is intentionally not a test, it's a generic function used by the tests below.
2648    fn test_eq_methods_generic<T>(list: &[T])
2649    where
2650        T: PartialEq + PartialOrd + ToPyObject,
2651    {
2652        Python::with_gil(|py| {
2653            for a in list {
2654                for b in list {
2655                    let a_py = a.to_object(py).into_bound(py);
2656                    let b_py = b.to_object(py).into_bound(py);
2657
2658                    assert_eq!(
2659                        a.lt(b),
2660                        a_py.lt(&b_py).unwrap(),
2661                        "{} < {} should be {}.",
2662                        a_py,
2663                        b_py,
2664                        a.lt(b)
2665                    );
2666                    assert_eq!(
2667                        a.le(b),
2668                        a_py.le(&b_py).unwrap(),
2669                        "{} <= {} should be {}.",
2670                        a_py,
2671                        b_py,
2672                        a.le(b)
2673                    );
2674                    assert_eq!(
2675                        a.eq(b),
2676                        a_py.eq(&b_py).unwrap(),
2677                        "{} == {} should be {}.",
2678                        a_py,
2679                        b_py,
2680                        a.eq(b)
2681                    );
2682                    assert_eq!(
2683                        a.ne(b),
2684                        a_py.ne(&b_py).unwrap(),
2685                        "{} != {} should be {}.",
2686                        a_py,
2687                        b_py,
2688                        a.ne(b)
2689                    );
2690                    assert_eq!(
2691                        a.gt(b),
2692                        a_py.gt(&b_py).unwrap(),
2693                        "{} > {} should be {}.",
2694                        a_py,
2695                        b_py,
2696                        a.gt(b)
2697                    );
2698                    assert_eq!(
2699                        a.ge(b),
2700                        a_py.ge(&b_py).unwrap(),
2701                        "{} >= {} should be {}.",
2702                        a_py,
2703                        b_py,
2704                        a.ge(b)
2705                    );
2706                }
2707            }
2708        });
2709    }
2710
2711    #[test]
2712    fn test_eq_methods_integers() {
2713        let ints = [-4, -4, 1, 2, 0, -100, 1_000_000];
2714        test_eq_methods_generic(&ints);
2715    }
2716
2717    #[test]
2718    fn test_eq_methods_strings() {
2719        let strings = ["Let's", "test", "some", "eq", "methods"];
2720        test_eq_methods_generic(&strings);
2721    }
2722
2723    #[test]
2724    fn test_eq_methods_floats() {
2725        let floats = [
2726            -1.0,
2727            2.5,
2728            0.0,
2729            3.0,
2730            std::f64::consts::PI,
2731            10.0,
2732            10.0 / 3.0,
2733            -1_000_000.0,
2734        ];
2735        test_eq_methods_generic(&floats);
2736    }
2737
2738    #[test]
2739    fn test_eq_methods_bools() {
2740        let bools = [true, false];
2741        test_eq_methods_generic(&bools);
2742    }
2743
2744    #[test]
2745    fn test_rich_compare_type_error() {
2746        Python::with_gil(|py| {
2747            let py_int = 1.to_object(py).into_bound(py);
2748            let py_str = "1".to_object(py).into_bound(py);
2749
2750            assert!(py_int.rich_compare(&py_str, CompareOp::Lt).is_err());
2751            assert!(!py_int
2752                .rich_compare(py_str, CompareOp::Eq)
2753                .unwrap()
2754                .is_truthy()
2755                .unwrap());
2756        })
2757    }
2758
2759    #[test]
2760    fn test_is_ellipsis() {
2761        Python::with_gil(|py| {
2762            let v = py
2763                .eval_bound("...", None, None)
2764                .map_err(|e| e.display(py))
2765                .unwrap();
2766
2767            assert!(v.is_ellipsis());
2768
2769            let not_ellipsis = 5.to_object(py).into_bound(py);
2770            assert!(!not_ellipsis.is_ellipsis());
2771        });
2772    }
2773
2774    #[test]
2775    fn test_is_callable() {
2776        Python::with_gil(|py| {
2777            assert!(PyList::type_object_bound(py).is_callable());
2778
2779            let not_callable = 5.to_object(py).into_bound(py);
2780            assert!(!not_callable.is_callable());
2781        });
2782    }
2783
2784    #[test]
2785    fn test_is_empty() {
2786        Python::with_gil(|py| {
2787            let empty_list = PyList::empty_bound(py).into_any();
2788            assert!(empty_list.is_empty().unwrap());
2789
2790            let list = PyList::new_bound(py, vec![1, 2, 3]).into_any();
2791            assert!(!list.is_empty().unwrap());
2792
2793            let not_container = 5.to_object(py).into_bound(py);
2794            assert!(not_container.is_empty().is_err());
2795        });
2796    }
2797
2798    #[cfg(feature = "macros")]
2799    #[test]
2800    #[allow(unknown_lints, non_local_definitions)]
2801    fn test_fallible_dir() {
2802        use crate::exceptions::PyValueError;
2803        use crate::prelude::*;
2804
2805        #[pyclass(crate = "crate")]
2806        struct DirFail;
2807
2808        #[pymethods(crate = "crate")]
2809        impl DirFail {
2810            fn __dir__(&self) -> PyResult<PyObject> {
2811                Err(PyValueError::new_err("uh-oh!"))
2812            }
2813        }
2814
2815        Python::with_gil(|py| {
2816            let obj = Bound::new(py, DirFail).unwrap();
2817            assert!(obj.dir().unwrap_err().is_instance_of::<PyValueError>(py));
2818        })
2819    }
2820}