Skip to main content

pyo3/types/
any.rs

1use crate::call::PyCallArgs;
2use crate::class::basic::CompareOp;
3use crate::conversion::{FromPyObject, IntoPyObject};
4use crate::err::{PyErr, PyResult};
5use crate::exceptions::PyTypeError;
6use crate::ffi_ptr_ext::FfiPtrExt;
7#[cfg(not(all(Py_LIMITED_API, Py_GIL_DISABLED)))]
8use crate::impl_::pycell::{PyClassObjectBase, PyStaticClassObject};
9use crate::instance::Bound;
10use crate::internal::get_slot::TP_DESCR_GET;
11use crate::py_result_ext::PyResultExt;
12use crate::type_object::{PyTypeCheck, PyTypeInfo};
13use crate::types::PySuper;
14use crate::types::{PyDict, PyIterator, PyList, PyString, PyType};
15use crate::{Borrowed, BoundObject, IntoPyObjectExt, Py, err, ffi};
16#[cfg(RustPython)]
17use crate::{sync::PyOnceLock, types::typeobject::PyTypeMethods};
18use core::cell::UnsafeCell;
19use core::cmp::Ordering;
20use core::ffi::c_int;
21use core::ptr;
22
23/// Represents any Python object.
24///
25/// Values of this type are accessed via PyO3's smart pointers, e.g. as
26/// [`Py<PyAny>`][crate::Py] or [`Bound<'py, PyAny>`][Bound].
27///
28/// For APIs available on all Python objects, see the [`PyAnyMethods`] trait which is implemented for
29/// [`Bound<'py, PyAny>`][Bound].
30///
31/// See
32#[doc = concat!("[the guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html#concrete-python-types)")]
33/// for an explanation of the different Python object types.
34#[repr(transparent)]
35pub struct PyAny(UnsafeCell<ffi::PyObject>);
36
37#[allow(non_snake_case)]
38// Originally ffi::object::PyObject_Check, but this is not in the Python C API.
39fn PyObject_Check(_: *mut ffi::PyObject) -> c_int {
40    1
41}
42
43// We follow stub writing guidelines and use "object" instead of "typing.Any": https://typing.python.org/en/latest/guides/writing_stubs.html#using-any
44#[cfg(not(RustPython))]
45pyobject_native_type_info!(
46    PyAny,
47    pyobject_native_static_type_object!(ffi::PyBaseObject_Type),
48    "typing",
49    "Any",
50    Some("builtins"),
51    #checkfunction=PyObject_Check
52);
53
54#[cfg(RustPython)]
55pyobject_native_type_info!(
56    PyAny,
57    |py| {
58        static TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();
59        TYPE.import(py, "builtins", "object").unwrap().as_type_ptr()
60    },
61    "typing",
62    "Any",
63    Some("builtins"),
64    #checkfunction=PyObject_Check
65);
66
67pyobject_native_type_sized!(PyAny, ffi::PyObject);
68// We could use pyobject_subclassable_native_type for all builds here, but for
69// now only on opaque PyObject builds to not introduce unintended behavior
70// changes on older Python releases.
71//
72// The difference is that pyobject_subclassable_native_type will use variable
73// object size for inheritance rather than PyStaticClassObject
74#[cfg(not(all(Py_LIMITED_API, Py_GIL_DISABLED)))]
75impl crate::impl_::pyclass::PyClassBaseType for PyAny {
76    type LayoutAsBase = PyClassObjectBase<ffi::PyObject>;
77    type BaseNativeType = PyAny;
78    type Initializer = crate::impl_::pyclass_init::PyNativeTypeInitializer<Self>;
79    type PyClassMutability = crate::pycell::impl_::ImmutableClass;
80    type Layout<T: crate::impl_::pyclass::PyClassImpl> = PyStaticClassObject<T>;
81}
82
83#[cfg(all(Py_LIMITED_API, Py_GIL_DISABLED))]
84pyobject_subclassable_native_type!(PyAny, ffi::PyObject);
85
86/// This trait represents the Python APIs which are usable on all Python objects.
87///
88/// It is recommended you import this trait via `use pyo3::prelude::*` rather than
89/// by importing this trait directly.
90#[doc(alias = "PyAny")]
91pub trait PyAnyMethods<'py>: crate::sealed::Sealed {
92    /// Returns whether `self` and `other` point to the same object. To compare
93    /// the equality of two objects (the `==` operator), use [`eq`](PyAnyMethods::eq).
94    ///
95    /// This is equivalent to the Python expression `self is other`.
96    fn is<T: AsRef<Py<PyAny>>>(&self, other: T) -> bool;
97
98    /// Determines whether this object has the given attribute.
99    ///
100    /// This is equivalent to the Python expression `hasattr(self, attr_name)`.
101    ///
102    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
103    /// to intern `attr_name`.
104    ///
105    /// # Example: `intern!`ing the attribute name
106    ///
107    /// ```
108    /// # use pyo3::{prelude::*, intern};
109    /// #
110    /// #[pyfunction]
111    /// fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> {
112    ///     sys.hasattr(intern!(sys.py(), "version"))
113    /// }
114    /// #
115    /// # Python::attach(|py| {
116    /// #    let sys = py.import("sys").unwrap();
117    /// #    has_version(&sys).unwrap();
118    /// # });
119    /// ```
120    fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
121    where
122        N: IntoPyObject<'py, Target = PyString>;
123
124    /// Retrieves an attribute value.
125    ///
126    /// This is equivalent to the Python expression `self.attr_name`.
127    ///
128    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
129    /// to intern `attr_name`.
130    ///
131    /// # Example: `intern!`ing the attribute name
132    ///
133    /// ```
134    /// # use pyo3::{prelude::*, intern};
135    /// #
136    /// #[pyfunction]
137    /// fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> {
138    ///     sys.getattr(intern!(sys.py(), "version"))
139    /// }
140    /// #
141    /// # Python::attach(|py| {
142    /// #    let sys = py.import("sys").unwrap();
143    /// #    version(&sys).unwrap();
144    /// # });
145    /// ```
146    fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
147    where
148        N: IntoPyObject<'py, Target = PyString>;
149
150    /// Retrieves an attribute value optionally.
151    ///
152    /// This is equivalent to the Python expression `getattr(self, attr_name, None)`, which may
153    /// be more efficient in some cases by simply returning `None` if the attribute is not found
154    /// instead of raising `AttributeError`.
155    ///
156    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
157    /// to intern `attr_name`.
158    ///
159    /// # Errors
160    /// Returns `Err` if an exception other than `AttributeError` is raised during attribute lookup,
161    /// such as a `ValueError` from a property or descriptor.
162    ///
163    /// # Example: Retrieving an optional attribute
164    /// ```
165    /// # use pyo3::{prelude::*, intern};
166    /// #
167    /// #[pyfunction]
168    /// fn get_version_if_exists<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Option<Bound<'py, PyAny>>> {
169    ///     sys.getattr_opt(intern!(sys.py(), "version"))
170    /// }
171    /// #
172    /// # Python::attach(|py| {
173    /// #    let sys = py.import("sys").unwrap();
174    /// #    let version = get_version_if_exists(&sys).unwrap();
175    /// #    assert!(version.is_some());
176    /// # });
177    /// ```
178    fn getattr_opt<N>(&self, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>
179    where
180        N: IntoPyObject<'py, Target = PyString>;
181
182    /// Sets an attribute value.
183    ///
184    /// This is equivalent to the Python expression `self.attr_name = value`.
185    ///
186    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
187    /// to intern `name`.
188    ///
189    /// # Example: `intern!`ing the attribute name
190    ///
191    /// ```
192    /// # use pyo3::{prelude::*, intern};
193    /// #
194    /// #[pyfunction]
195    /// fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> {
196    ///     ob.setattr(intern!(ob.py(), "answer"), 42)
197    /// }
198    /// #
199    /// # Python::attach(|py| {
200    /// #    let ob = PyModule::new(py, "empty").unwrap();
201    /// #    set_answer(&ob).unwrap();
202    /// # });
203    /// ```
204    fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
205    where
206        N: IntoPyObject<'py, Target = PyString>,
207        V: IntoPyObject<'py>;
208
209    /// Deletes an attribute.
210    ///
211    /// This is equivalent to the Python statement `del self.attr_name`.
212    ///
213    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
214    /// to intern `attr_name`.
215    fn delattr<N>(&self, attr_name: N) -> PyResult<()>
216    where
217        N: IntoPyObject<'py, Target = PyString>;
218
219    /// Returns an [`Ordering`] between `self` and `other`.
220    ///
221    /// This is equivalent to the following Python code:
222    /// ```python
223    /// if self == other:
224    ///     return Equal
225    /// elif a < b:
226    ///     return Less
227    /// elif a > b:
228    ///     return Greater
229    /// else:
230    ///     raise TypeError("PyAny::compare(): All comparisons returned false")
231    /// ```
232    ///
233    /// # Examples
234    ///
235    /// ```rust
236    /// use pyo3::prelude::*;
237    /// use pyo3::types::PyFloat;
238    /// use core::cmp::Ordering;
239    ///
240    /// # fn main() -> PyResult<()> {
241    /// Python::attach(|py| -> PyResult<()> {
242    ///     let a = PyFloat::new(py, 0_f64);
243    ///     let b = PyFloat::new(py, 42_f64);
244    ///     assert_eq!(a.compare(b)?, Ordering::Less);
245    ///     Ok(())
246    /// })?;
247    /// # Ok(())}
248    /// ```
249    ///
250    /// It will return `PyErr` for values that cannot be compared:
251    ///
252    /// ```rust
253    /// use pyo3::prelude::*;
254    /// use pyo3::types::{PyFloat, PyString};
255    ///
256    /// # fn main() -> PyResult<()> {
257    /// Python::attach(|py| -> PyResult<()> {
258    ///     let a = PyFloat::new(py, 0_f64);
259    ///     let b = PyString::new(py, "zero");
260    ///     assert!(a.compare(b).is_err());
261    ///     Ok(())
262    /// })?;
263    /// # Ok(())}
264    /// ```
265    fn compare<O>(&self, other: O) -> PyResult<Ordering>
266    where
267        O: IntoPyObject<'py>;
268
269    /// Tests whether two Python objects obey a given [`CompareOp`].
270    ///
271    /// [`lt`](Self::lt), [`le`](Self::le), [`eq`](Self::eq), [`ne`](Self::ne),
272    /// [`gt`](Self::gt) and [`ge`](Self::ge) are the specialized versions
273    /// of this function.
274    ///
275    /// Depending on the value of `compare_op`, this is equivalent to one of the
276    /// following Python expressions:
277    ///
278    /// | `compare_op` | Python expression |
279    /// | :---: | :----: |
280    /// | [`CompareOp::Eq`] | `self == other` |
281    /// | [`CompareOp::Ne`] | `self != other` |
282    /// | [`CompareOp::Lt`] | `self < other` |
283    /// | [`CompareOp::Le`] | `self <= other` |
284    /// | [`CompareOp::Gt`] | `self > other` |
285    /// | [`CompareOp::Ge`] | `self >= other` |
286    ///
287    /// # Examples
288    ///
289    /// ```rust
290    /// use pyo3::class::basic::CompareOp;
291    /// use pyo3::prelude::*;
292    ///
293    /// # fn main() -> PyResult<()> {
294    /// Python::attach(|py| -> PyResult<()> {
295    ///     let a = 0_u8.into_pyobject(py)?;
296    ///     let b = 42_u8.into_pyobject(py)?;
297    ///     assert!(a.rich_compare(b, CompareOp::Le)?.is_truthy()?);
298    ///     Ok(())
299    /// })?;
300    /// # Ok(())}
301    /// ```
302    fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>>
303    where
304        O: IntoPyObject<'py>;
305
306    /// Computes the negative of self.
307    ///
308    /// Equivalent to the Python expression `-self`.
309    fn neg(&self) -> PyResult<Bound<'py, PyAny>>;
310
311    /// Computes the positive of self.
312    ///
313    /// Equivalent to the Python expression `+self`.
314    fn pos(&self) -> PyResult<Bound<'py, PyAny>>;
315
316    /// Computes the absolute of self.
317    ///
318    /// Equivalent to the Python expression `abs(self)`.
319    fn abs(&self) -> PyResult<Bound<'py, PyAny>>;
320
321    /// Computes `~self`.
322    fn bitnot(&self) -> PyResult<Bound<'py, PyAny>>;
323
324    /// Tests whether this object is less than another.
325    ///
326    /// This is equivalent to the Python expression `self < other`.
327    fn lt<O>(&self, other: O) -> PyResult<bool>
328    where
329        O: IntoPyObject<'py>;
330
331    /// Tests whether this object is less than or equal to another.
332    ///
333    /// This is equivalent to the Python expression `self <= other`.
334    fn le<O>(&self, other: O) -> PyResult<bool>
335    where
336        O: IntoPyObject<'py>;
337
338    /// Tests whether this object is equal to another.
339    ///
340    /// This is equivalent to the Python expression `self == other`.
341    fn eq<O>(&self, other: O) -> PyResult<bool>
342    where
343        O: IntoPyObject<'py>;
344
345    /// Tests whether this object is not equal to another.
346    ///
347    /// This is equivalent to the Python expression `self != other`.
348    fn ne<O>(&self, other: O) -> PyResult<bool>
349    where
350        O: IntoPyObject<'py>;
351
352    /// Tests whether this object is greater than another.
353    ///
354    /// This is equivalent to the Python expression `self > other`.
355    fn gt<O>(&self, other: O) -> PyResult<bool>
356    where
357        O: IntoPyObject<'py>;
358
359    /// Tests whether this object is greater than or equal to another.
360    ///
361    /// This is equivalent to the Python expression `self >= other`.
362    fn ge<O>(&self, other: O) -> PyResult<bool>
363    where
364        O: IntoPyObject<'py>;
365
366    /// Computes `self + other`.
367    fn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
368    where
369        O: IntoPyObject<'py>;
370
371    /// Computes `self - other`.
372    fn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
373    where
374        O: IntoPyObject<'py>;
375
376    /// Computes `self * other`.
377    fn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
378    where
379        O: IntoPyObject<'py>;
380
381    /// Computes `self @ other`.
382    fn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
383    where
384        O: IntoPyObject<'py>;
385
386    /// Computes `self / other`.
387    fn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
388    where
389        O: IntoPyObject<'py>;
390
391    /// Computes `self // other`.
392    fn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
393    where
394        O: IntoPyObject<'py>;
395
396    /// Computes `self % other`.
397    fn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
398    where
399        O: IntoPyObject<'py>;
400
401    /// Computes `divmod(self, other)`.
402    fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
403    where
404        O: IntoPyObject<'py>;
405
406    /// Computes `self << other`.
407    fn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
408    where
409        O: IntoPyObject<'py>;
410
411    /// Computes `self >> other`.
412    fn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
413    where
414        O: IntoPyObject<'py>;
415
416    /// Computes `self ** other % modulus` (`pow(self, other, modulus)`).
417    /// `py.None()` may be passed for the `modulus`.
418    fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>
419    where
420        O1: IntoPyObject<'py>,
421        O2: IntoPyObject<'py>;
422
423    /// Computes `self & other`.
424    fn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
425    where
426        O: IntoPyObject<'py>;
427
428    /// Computes `self | other`.
429    fn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
430    where
431        O: IntoPyObject<'py>;
432
433    /// Computes `self ^ other`.
434    fn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
435    where
436        O: IntoPyObject<'py>;
437
438    /// Determines whether this object appears callable.
439    ///
440    /// This is equivalent to Python's [`callable()`][1] function.
441    ///
442    /// # Examples
443    ///
444    /// ```rust
445    /// use pyo3::prelude::*;
446    ///
447    /// # fn main() -> PyResult<()> {
448    /// Python::attach(|py| -> PyResult<()> {
449    ///     let builtins = PyModule::import(py, "builtins")?;
450    ///     let print = builtins.getattr("print")?;
451    ///     assert!(print.is_callable());
452    ///     Ok(())
453    /// })?;
454    /// # Ok(())}
455    /// ```
456    ///
457    /// This is equivalent to the Python statement `assert callable(print)`.
458    ///
459    /// Note that unless an API needs to distinguish between callable and
460    /// non-callable objects, there is no point in checking for callability.
461    /// Instead, it is better to just do the call and handle potential
462    /// exceptions.
463    ///
464    /// [1]: https://docs.python.org/3/library/functions.html#callable
465    fn is_callable(&self) -> bool;
466
467    /// Calls the object.
468    ///
469    /// This is equivalent to the Python expression `self(*args, **kwargs)`.
470    ///
471    /// # Examples
472    ///
473    /// ```rust
474    /// use pyo3::prelude::*;
475    /// use pyo3::types::PyDict;
476    /// use pyo3_ffi::c_str;
477    /// use core::ffi::CStr;
478    ///
479    /// const CODE: &CStr = cr#"
480    /// def function(*args, **kwargs):
481    ///     assert args == ("hello",)
482    ///     assert kwargs == {"cruel": "world"}
483    ///     return "called with args and kwargs"
484    /// "#;
485    ///
486    /// # fn main() -> PyResult<()> {
487    /// Python::attach(|py| {
488    ///     let module = PyModule::from_code(py, CODE, c"func.py", c"")?;
489    ///     let fun = module.getattr("function")?;
490    ///     let args = ("hello",);
491    ///     let kwargs = PyDict::new(py);
492    ///     kwargs.set_item("cruel", "world")?;
493    ///     let result = fun.call(args, Some(&kwargs))?;
494    ///     assert_eq!(result.extract::<String>()?, "called with args and kwargs");
495    ///     Ok(())
496    /// })
497    /// # }
498    /// ```
499    fn call<A>(&self, args: A, kwargs: Option<&Bound<'py, PyDict>>) -> PyResult<Bound<'py, PyAny>>
500    where
501        A: PyCallArgs<'py>;
502
503    /// Calls the object without arguments.
504    ///
505    /// This is equivalent to the Python expression `self()`.
506    ///
507    /// # Examples
508    ///
509    /// ```no_run
510    /// use pyo3::prelude::*;
511    ///
512    /// # fn main() -> PyResult<()> {
513    /// Python::attach(|py| -> PyResult<()> {
514    ///     let module = PyModule::import(py, "builtins")?;
515    ///     let help = module.getattr("help")?;
516    ///     help.call0()?;
517    ///     Ok(())
518    /// })?;
519    /// # Ok(())}
520    /// ```
521    ///
522    /// This is equivalent to the Python expression `help()`.
523    fn call0(&self) -> PyResult<Bound<'py, PyAny>>;
524
525    /// Calls the object with only positional arguments.
526    ///
527    /// This is equivalent to the Python expression `self(*args)`.
528    ///
529    /// # Examples
530    ///
531    /// ```rust
532    /// use pyo3::prelude::*;
533    /// use pyo3_ffi::c_str;
534    /// use core::ffi::CStr;
535    ///
536    /// const CODE: &CStr = cr#"
537    /// def function(*args, **kwargs):
538    ///     assert args == ("hello",)
539    ///     assert kwargs == {}
540    ///     return "called with args"
541    /// "#;
542    ///
543    /// # fn main() -> PyResult<()> {
544    /// Python::attach(|py| {
545    ///     let module = PyModule::from_code(py, CODE, c"func.py", c"")?;
546    ///     let fun = module.getattr("function")?;
547    ///     let args = ("hello",);
548    ///     let result = fun.call1(args)?;
549    ///     assert_eq!(result.extract::<String>()?, "called with args");
550    ///     Ok(())
551    /// })
552    /// # }
553    /// ```
554    fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>>
555    where
556        A: PyCallArgs<'py>;
557
558    /// Calls a method on the object.
559    ///
560    /// This is equivalent to the Python expression `self.name(*args, **kwargs)`.
561    ///
562    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
563    /// to intern `name`.
564    ///
565    /// # Examples
566    ///
567    /// ```rust
568    /// use pyo3::prelude::*;
569    /// use pyo3::types::PyDict;
570    /// use pyo3_ffi::c_str;
571    /// use core::ffi::CStr;
572    ///
573    /// const CODE: &CStr = cr#"
574    /// class A:
575    ///     def method(self, *args, **kwargs):
576    ///         assert args == ("hello",)
577    ///         assert kwargs == {"cruel": "world"}
578    ///         return "called with args and kwargs"
579    /// a = A()
580    /// "#;
581    ///
582    /// # fn main() -> PyResult<()> {
583    /// Python::attach(|py| {
584    ///     let module = PyModule::from_code(py, CODE, c"a.py", c"")?;
585    ///     let instance = module.getattr("a")?;
586    ///     let args = ("hello",);
587    ///     let kwargs = PyDict::new(py);
588    ///     kwargs.set_item("cruel", "world")?;
589    ///     let result = instance.call_method("method", args, Some(&kwargs))?;
590    ///     assert_eq!(result.extract::<String>()?, "called with args and kwargs");
591    ///     Ok(())
592    /// })
593    /// # }
594    /// ```
595    fn call_method<N, A>(
596        &self,
597        name: N,
598        args: A,
599        kwargs: Option<&Bound<'py, PyDict>>,
600    ) -> PyResult<Bound<'py, PyAny>>
601    where
602        N: IntoPyObject<'py, Target = PyString>,
603        A: PyCallArgs<'py>;
604
605    /// Calls a method on the object without arguments.
606    ///
607    /// This is equivalent to the Python expression `self.name()`.
608    ///
609    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
610    /// to intern `name`.
611    ///
612    /// # Examples
613    ///
614    /// ```rust
615    /// use pyo3::prelude::*;
616    /// use pyo3_ffi::c_str;
617    /// use core::ffi::CStr;
618    ///
619    /// const CODE: &CStr = cr#"
620    /// class A:
621    ///     def method(self, *args, **kwargs):
622    ///         assert args == ()
623    ///         assert kwargs == {}
624    ///         return "called with no arguments"
625    /// a = A()
626    /// "#;
627    ///
628    /// # fn main() -> PyResult<()> {
629    /// Python::attach(|py| {
630    ///     let module = PyModule::from_code(py, CODE, c"a.py", c"")?;
631    ///     let instance = module.getattr("a")?;
632    ///     let result = instance.call_method0("method")?;
633    ///     assert_eq!(result.extract::<String>()?, "called with no arguments");
634    ///     Ok(())
635    /// })
636    /// # }
637    /// ```
638    fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
639    where
640        N: IntoPyObject<'py, Target = PyString>;
641
642    /// Calls a method on the object with only positional arguments.
643    ///
644    /// This is equivalent to the Python expression `self.name(*args)`.
645    ///
646    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
647    /// to intern `name`.
648    ///
649    /// # Examples
650    ///
651    /// ```rust
652    /// use pyo3::prelude::*;
653    /// use pyo3_ffi::c_str;
654    /// use core::ffi::CStr;
655    ///
656    /// const CODE: &CStr = cr#"
657    /// class A:
658    ///     def method(self, *args, **kwargs):
659    ///         assert args == ("hello",)
660    ///         assert kwargs == {}
661    ///         return "called with args"
662    /// a = A()
663    /// "#;
664    ///
665    /// # fn main() -> PyResult<()> {
666    /// Python::attach(|py| {
667    ///     let module = PyModule::from_code(py, CODE, c"a.py", c"")?;
668    ///     let instance = module.getattr("a")?;
669    ///     let args = ("hello",);
670    ///     let result = instance.call_method1("method", args)?;
671    ///     assert_eq!(result.extract::<String>()?, "called with args");
672    ///     Ok(())
673    /// })
674    /// # }
675    /// ```
676    fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>>
677    where
678        N: IntoPyObject<'py, Target = PyString>,
679        A: PyCallArgs<'py>;
680
681    /// Returns whether the object is considered to be true.
682    ///
683    /// This is equivalent to the Python expression `bool(self)`.
684    fn is_truthy(&self) -> PyResult<bool>;
685
686    /// Returns whether the object is considered to be None.
687    ///
688    /// This is equivalent to the Python expression `self is None`.
689    fn is_none(&self) -> bool;
690
691    /// Returns true if the sequence or mapping has a length of 0.
692    ///
693    /// This is equivalent to the Python expression `len(self) == 0`.
694    fn is_empty(&self) -> PyResult<bool>;
695
696    /// Gets an item from the collection.
697    ///
698    /// This is equivalent to the Python expression `self[key]`.
699    fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>
700    where
701        K: IntoPyObject<'py>;
702
703    /// Sets a collection item value.
704    ///
705    /// This is equivalent to the Python expression `self[key] = value`.
706    fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
707    where
708        K: IntoPyObject<'py>,
709        V: IntoPyObject<'py>;
710
711    /// Deletes an item from the collection.
712    ///
713    /// This is equivalent to the Python expression `del self[key]`.
714    fn del_item<K>(&self, key: K) -> PyResult<()>
715    where
716        K: IntoPyObject<'py>;
717
718    /// Takes an object and returns an iterator for it. Returns an error if the object is not
719    /// iterable.
720    ///
721    /// This is typically a new iterator but if the argument is an iterator,
722    /// this returns itself.
723    ///
724    /// # Example: Checking a Python object for iterability
725    ///
726    /// ```rust
727    /// use pyo3::prelude::*;
728    /// use pyo3::types::{PyAny, PyNone};
729    ///
730    /// fn is_iterable(obj: &Bound<'_, PyAny>) -> bool {
731    ///     match obj.try_iter() {
732    ///         Ok(_) => true,
733    ///         Err(_) => false,
734    ///     }
735    /// }
736    ///
737    /// Python::attach(|py| {
738    ///     assert!(is_iterable(&vec![1, 2, 3].into_pyobject(py).unwrap()));
739    ///     assert!(!is_iterable(&PyNone::get(py)));
740    /// });
741    /// ```
742    fn try_iter(&self) -> PyResult<Bound<'py, PyIterator>>;
743
744    /// Returns the Python type object for this object's type.
745    fn get_type(&self) -> Bound<'py, PyType>;
746
747    /// Returns the Python type pointer for this object.
748    fn get_type_ptr(&self) -> *mut ffi::PyTypeObject;
749
750    /// Extracts some type from the Python object.
751    ///
752    /// This is a wrapper function around [`FromPyObject::extract()`](crate::FromPyObject::extract).
753    fn extract<'a, T>(&'a self) -> Result<T, T::Error>
754    where
755        T: FromPyObject<'a, 'py>;
756
757    /// Computes the "repr" representation of self.
758    ///
759    /// This is equivalent to the Python expression `repr(self)`.
760    fn repr(&self) -> PyResult<Bound<'py, PyString>>;
761
762    /// Computes the "str" representation of self.
763    ///
764    /// This is equivalent to the Python expression `str(self)`.
765    fn str(&self) -> PyResult<Bound<'py, PyString>>;
766
767    /// Retrieves the hash code of self.
768    ///
769    /// This is equivalent to the Python expression `hash(self)`.
770    fn hash(&self) -> PyResult<isize>;
771
772    /// Returns the length of the sequence or mapping.
773    ///
774    /// This is equivalent to the Python expression `len(self)`.
775    fn len(&self) -> PyResult<usize>;
776
777    /// Returns the list of attributes of this object.
778    ///
779    /// This is equivalent to the Python expression `dir(self)`.
780    fn dir(&self) -> PyResult<Bound<'py, PyList>>;
781
782    /// Checks whether this object is an instance of type `ty`.
783    ///
784    /// This is equivalent to the Python expression `isinstance(self, ty)`.
785    fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>;
786
787    /// Checks whether this object is an instance of exactly type `ty` (not a subclass).
788    ///
789    /// This is equivalent to the Python expression `type(self) is ty`.
790    fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool;
791
792    /// Checks whether this object is an instance of type `T`.
793    ///
794    /// This is equivalent to the Python expression `isinstance(self, T)`,
795    /// if the type `T` is known at compile time.
796    fn is_instance_of<T: PyTypeCheck>(&self) -> bool;
797
798    /// Checks whether this object is an instance of exactly type `T`.
799    ///
800    /// This is equivalent to the Python expression `type(self) is T`,
801    /// if the type `T` is known at compile time.
802    fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool;
803
804    /// Determines if self contains `value`.
805    ///
806    /// This is equivalent to the Python expression `value in self`.
807    fn contains<V>(&self, value: V) -> PyResult<bool>
808    where
809        V: IntoPyObject<'py>;
810
811    /// Return a proxy object that delegates method calls to a parent or sibling class of type.
812    ///
813    /// This is equivalent to the Python expression `super()`
814    fn py_super(&self) -> PyResult<Bound<'py, PySuper>>;
815}
816
817macro_rules! implement_binop {
818    ($name:ident, $c_api:ident, $op:expr) => {
819        #[doc = concat!("Computes `self ", $op, " other`.")]
820        fn $name<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
821        where
822            O: IntoPyObject<'py>,
823        {
824            let py = self.py();
825            let other = other.into_pyobject_or_pyerr(py)?;
826            unsafe { ffi::$c_api(self.as_ptr(), other.as_ptr()).assume_owned_or_err(py) }
827        }
828    };
829}
830
831impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
832    #[inline]
833    fn is<T: AsRef<Py<PyAny>>>(&self, other: T) -> bool {
834        ptr::eq(self.as_ptr(), other.as_ref().as_ptr())
835    }
836
837    fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
838    where
839        N: IntoPyObject<'py, Target = PyString>,
840    {
841        let py = self.py();
842        let attr_name = attr_name.into_pyobject(py).map_err(Into::into)?;
843        match unsafe { ffi::compat::PyObject_HasAttrWithError(self.as_ptr(), attr_name.as_ptr()) } {
844            1 => Ok(true),
845            0 => Ok(false),
846            _ => Err(PyErr::fetch(py)),
847        }
848    }
849
850    fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
851    where
852        N: IntoPyObject<'py, Target = PyString>,
853    {
854        let py = self.py();
855        let attr_name = attr_name.into_pyobject(py).map_err(Into::into)?;
856        unsafe { ffi::PyObject_GetAttr(self.as_ptr(), attr_name.as_ptr()).assume_owned_or_err(py) }
857    }
858
859    fn getattr_opt<N>(&self, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>
860    where
861        N: IntoPyObject<'py, Target = PyString>,
862    {
863        let py = self.py();
864        let attr_name = attr_name.into_pyobject_or_pyerr(py)?;
865        let mut resp_ptr: *mut ffi::PyObject = core::ptr::null_mut();
866        match unsafe {
867            ffi::compat::PyObject_GetOptionalAttr(self.as_ptr(), attr_name.as_ptr(), &mut resp_ptr)
868        } {
869            // Attribute found, result is a new strong reference
870            1 => Ok(Some(unsafe { resp_ptr.assume_owned_unchecked(py) })),
871            // Attribute not found
872            0 => Ok(None),
873            // An error occurred (other than AttributeError)
874            _ => Err(PyErr::fetch(py)),
875        }
876    }
877
878    fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
879    where
880        N: IntoPyObject<'py, Target = PyString>,
881        V: IntoPyObject<'py>,
882    {
883        let py = self.py();
884        let attr_name = attr_name.into_pyobject_or_pyerr(py)?;
885        let value = value.into_pyobject_or_pyerr(py)?;
886        err::error_on_negative(py, unsafe {
887            ffi::PyObject_SetAttr(self.as_ptr(), attr_name.as_ptr(), value.as_ptr())
888        })
889    }
890
891    fn delattr<N>(&self, attr_name: N) -> PyResult<()>
892    where
893        N: IntoPyObject<'py, Target = PyString>,
894    {
895        let py = self.py();
896        let attr_name = attr_name.into_pyobject_or_pyerr(py)?;
897        err::error_on_negative(py, unsafe {
898            ffi::PyObject_DelAttr(self.as_ptr(), attr_name.as_ptr())
899        })
900    }
901
902    fn compare<O>(&self, other: O) -> PyResult<Ordering>
903    where
904        O: IntoPyObject<'py>,
905    {
906        fn inner(any: &Bound<'_, PyAny>, other: Borrowed<'_, '_, PyAny>) -> PyResult<Ordering> {
907            let other = other.as_ptr();
908            // Almost the same as ffi::PyObject_RichCompareBool, but this one doesn't try self == other.
909            // See https://github.com/PyO3/pyo3/issues/985 for more.
910            let do_compare = |other, op| unsafe {
911                ffi::PyObject_RichCompare(any.as_ptr(), other, op)
912                    .assume_owned_or_err(any.py())
913                    .and_then(|obj| obj.is_truthy())
914            };
915            if do_compare(other, ffi::Py_EQ)? {
916                Ok(Ordering::Equal)
917            } else if do_compare(other, ffi::Py_LT)? {
918                Ok(Ordering::Less)
919            } else if do_compare(other, ffi::Py_GT)? {
920                Ok(Ordering::Greater)
921            } else {
922                Err(PyTypeError::new_err(
923                    "PyAny::compare(): All comparisons returned false",
924                ))
925            }
926        }
927
928        let py = self.py();
929        inner(
930            self,
931            other.into_pyobject_or_pyerr(py)?.into_any().as_borrowed(),
932        )
933    }
934
935    fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>>
936    where
937        O: IntoPyObject<'py>,
938    {
939        let py = self.py();
940        let other = other.into_pyobject_or_pyerr(py)?;
941        unsafe {
942            ffi::PyObject_RichCompare(self.as_ptr(), other.as_ptr(), compare_op as c_int)
943                .assume_owned_or_err(py)
944        }
945    }
946
947    fn neg(&self) -> PyResult<Bound<'py, PyAny>> {
948        unsafe { ffi::PyNumber_Negative(self.as_ptr()).assume_owned_or_err(self.py()) }
949    }
950
951    fn pos(&self) -> PyResult<Bound<'py, PyAny>> {
952        fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
953            unsafe { ffi::PyNumber_Positive(any.as_ptr()).assume_owned_or_err(any.py()) }
954        }
955
956        inner(self)
957    }
958
959    fn abs(&self) -> PyResult<Bound<'py, PyAny>> {
960        fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
961            unsafe { ffi::PyNumber_Absolute(any.as_ptr()).assume_owned_or_err(any.py()) }
962        }
963
964        inner(self)
965    }
966
967    fn bitnot(&self) -> PyResult<Bound<'py, PyAny>> {
968        fn inner<'py>(any: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
969            unsafe { ffi::PyNumber_Invert(any.as_ptr()).assume_owned_or_err(any.py()) }
970        }
971
972        inner(self)
973    }
974
975    fn lt<O>(&self, other: O) -> PyResult<bool>
976    where
977        O: IntoPyObject<'py>,
978    {
979        self.rich_compare(other, CompareOp::Lt)
980            .and_then(|any| any.is_truthy())
981    }
982
983    fn le<O>(&self, other: O) -> PyResult<bool>
984    where
985        O: IntoPyObject<'py>,
986    {
987        self.rich_compare(other, CompareOp::Le)
988            .and_then(|any| any.is_truthy())
989    }
990
991    fn eq<O>(&self, other: O) -> PyResult<bool>
992    where
993        O: IntoPyObject<'py>,
994    {
995        self.rich_compare(other, CompareOp::Eq)
996            .and_then(|any| any.is_truthy())
997    }
998
999    fn ne<O>(&self, other: O) -> PyResult<bool>
1000    where
1001        O: IntoPyObject<'py>,
1002    {
1003        self.rich_compare(other, CompareOp::Ne)
1004            .and_then(|any| any.is_truthy())
1005    }
1006
1007    fn gt<O>(&self, other: O) -> PyResult<bool>
1008    where
1009        O: IntoPyObject<'py>,
1010    {
1011        self.rich_compare(other, CompareOp::Gt)
1012            .and_then(|any| any.is_truthy())
1013    }
1014
1015    fn ge<O>(&self, other: O) -> PyResult<bool>
1016    where
1017        O: IntoPyObject<'py>,
1018    {
1019        self.rich_compare(other, CompareOp::Ge)
1020            .and_then(|any| any.is_truthy())
1021    }
1022
1023    implement_binop!(add, PyNumber_Add, "+");
1024    implement_binop!(sub, PyNumber_Subtract, "-");
1025    implement_binop!(mul, PyNumber_Multiply, "*");
1026    implement_binop!(matmul, PyNumber_MatrixMultiply, "@");
1027    implement_binop!(div, PyNumber_TrueDivide, "/");
1028    implement_binop!(floor_div, PyNumber_FloorDivide, "//");
1029    implement_binop!(rem, PyNumber_Remainder, "%");
1030    implement_binop!(lshift, PyNumber_Lshift, "<<");
1031    implement_binop!(rshift, PyNumber_Rshift, ">>");
1032    implement_binop!(bitand, PyNumber_And, "&");
1033    implement_binop!(bitor, PyNumber_Or, "|");
1034    implement_binop!(bitxor, PyNumber_Xor, "^");
1035
1036    /// Computes `divmod(self, other)`.
1037    fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
1038    where
1039        O: IntoPyObject<'py>,
1040    {
1041        let py = self.py();
1042        let other = other.into_pyobject_or_pyerr(py)?;
1043        unsafe { ffi::PyNumber_Divmod(self.as_ptr(), other.as_ptr()).assume_owned_or_err(py) }
1044    }
1045
1046    /// Computes `self ** other % modulus` (`pow(self, other, modulus)`).
1047    /// `py.None()` may be passed for the `modulus`.
1048    fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>
1049    where
1050        O1: IntoPyObject<'py>,
1051        O2: IntoPyObject<'py>,
1052    {
1053        let py = self.py();
1054        let other = other.into_pyobject_or_pyerr(py)?;
1055        let modulus = modulus.into_pyobject_or_pyerr(py)?;
1056        unsafe {
1057            ffi::PyNumber_Power(self.as_ptr(), other.as_ptr(), modulus.as_ptr())
1058                .assume_owned_or_err(py)
1059        }
1060    }
1061
1062    fn is_callable(&self) -> bool {
1063        unsafe { ffi::PyCallable_Check(self.as_ptr()) != 0 }
1064    }
1065
1066    fn call<A>(&self, args: A, kwargs: Option<&Bound<'py, PyDict>>) -> PyResult<Bound<'py, PyAny>>
1067    where
1068        A: PyCallArgs<'py>,
1069    {
1070        if let Some(kwargs) = kwargs {
1071            args.call(
1072                self.as_borrowed(),
1073                kwargs.as_borrowed(),
1074                crate::call::private::Token,
1075            )
1076        } else {
1077            args.call_positional(self.as_borrowed(), crate::call::private::Token)
1078        }
1079    }
1080
1081    #[inline]
1082    fn call0(&self) -> PyResult<Bound<'py, PyAny>> {
1083        unsafe { ffi::compat::PyObject_CallNoArgs(self.as_ptr()).assume_owned_or_err(self.py()) }
1084    }
1085
1086    fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>>
1087    where
1088        A: PyCallArgs<'py>,
1089    {
1090        args.call_positional(self.as_borrowed(), crate::call::private::Token)
1091    }
1092
1093    #[inline]
1094    fn call_method<N, A>(
1095        &self,
1096        name: N,
1097        args: A,
1098        kwargs: Option<&Bound<'py, PyDict>>,
1099    ) -> PyResult<Bound<'py, PyAny>>
1100    where
1101        N: IntoPyObject<'py, Target = PyString>,
1102        A: PyCallArgs<'py>,
1103    {
1104        if kwargs.is_none() {
1105            self.call_method1(name, args)
1106        } else {
1107            self.getattr(name)
1108                .and_then(|method| method.call(args, kwargs))
1109        }
1110    }
1111
1112    #[inline]
1113    fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
1114    where
1115        N: IntoPyObject<'py, Target = PyString>,
1116    {
1117        let py = self.py();
1118        let name = name.into_pyobject_or_pyerr(py)?.into_bound();
1119        unsafe {
1120            ffi::compat::PyObject_CallMethodNoArgs(self.as_ptr(), name.as_ptr())
1121                .assume_owned_or_err(py)
1122        }
1123    }
1124
1125    fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>>
1126    where
1127        N: IntoPyObject<'py, Target = PyString>,
1128        A: PyCallArgs<'py>,
1129    {
1130        let name = name.into_pyobject_or_pyerr(self.py())?;
1131        args.call_method_positional(
1132            self.as_borrowed(),
1133            name.as_borrowed(),
1134            crate::call::private::Token,
1135        )
1136    }
1137
1138    fn is_truthy(&self) -> PyResult<bool> {
1139        let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) };
1140        err::error_on_negative(self.py(), v)?;
1141        Ok(v != 0)
1142    }
1143
1144    #[inline]
1145    fn is_none(&self) -> bool {
1146        unsafe { ptr::eq(ffi::Py_None(), self.as_ptr()) }
1147    }
1148
1149    fn is_empty(&self) -> PyResult<bool> {
1150        self.len().map(|l| l == 0)
1151    }
1152
1153    fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>
1154    where
1155        K: IntoPyObject<'py>,
1156    {
1157        let py = self.py();
1158        let key = key.into_pyobject_or_pyerr(py)?;
1159        unsafe { ffi::PyObject_GetItem(self.as_ptr(), key.as_ptr()).assume_owned_or_err(py) }
1160    }
1161
1162    fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
1163    where
1164        K: IntoPyObject<'py>,
1165        V: IntoPyObject<'py>,
1166    {
1167        let py = self.py();
1168        let key = key.into_pyobject_or_pyerr(py)?;
1169        let value = value.into_pyobject_or_pyerr(py)?;
1170        err::error_on_negative(py, unsafe {
1171            ffi::PyObject_SetItem(self.as_ptr(), key.as_ptr(), value.as_ptr())
1172        })
1173    }
1174
1175    fn del_item<K>(&self, key: K) -> PyResult<()>
1176    where
1177        K: IntoPyObject<'py>,
1178    {
1179        let py = self.py();
1180        let key = key.into_pyobject_or_pyerr(py)?;
1181        err::error_on_negative(py, unsafe {
1182            ffi::PyObject_DelItem(self.as_ptr(), key.as_ptr())
1183        })
1184    }
1185
1186    fn try_iter(&self) -> PyResult<Bound<'py, PyIterator>> {
1187        PyIterator::from_object(self)
1188    }
1189
1190    fn get_type(&self) -> Bound<'py, PyType> {
1191        unsafe { PyType::from_borrowed_type_ptr(self.py(), ffi::Py_TYPE(self.as_ptr())) }
1192    }
1193
1194    #[inline]
1195    fn get_type_ptr(&self) -> *mut ffi::PyTypeObject {
1196        unsafe { ffi::Py_TYPE(self.as_ptr()) }
1197    }
1198
1199    fn extract<'a, T>(&'a self) -> Result<T, T::Error>
1200    where
1201        T: FromPyObject<'a, 'py>,
1202    {
1203        FromPyObject::extract(self.as_borrowed())
1204    }
1205
1206    fn repr(&self) -> PyResult<Bound<'py, PyString>> {
1207        unsafe {
1208            ffi::PyObject_Repr(self.as_ptr())
1209                .assume_owned_or_err(self.py())
1210                .cast_into_unchecked()
1211        }
1212    }
1213
1214    fn str(&self) -> PyResult<Bound<'py, PyString>> {
1215        unsafe {
1216            ffi::PyObject_Str(self.as_ptr())
1217                .assume_owned_or_err(self.py())
1218                .cast_into_unchecked()
1219        }
1220    }
1221
1222    fn hash(&self) -> PyResult<isize> {
1223        // negative values other than -1 are valid hashes.
1224        match unsafe { ffi::PyObject_Hash(self.as_ptr()) } {
1225            -1 => Err(PyErr::fetch(self.py())),
1226            v => Ok(v),
1227        }
1228    }
1229
1230    fn len(&self) -> PyResult<usize> {
1231        let v = unsafe { ffi::PyObject_Size(self.as_ptr()) };
1232        err::error_on_negative(self.py(), v)?;
1233        Ok(v as usize)
1234    }
1235
1236    fn dir(&self) -> PyResult<Bound<'py, PyList>> {
1237        unsafe {
1238            ffi::PyObject_Dir(self.as_ptr())
1239                .assume_owned_or_err(self.py())
1240                .cast_into_unchecked()
1241        }
1242    }
1243
1244    #[inline]
1245    fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool> {
1246        let result = unsafe { ffi::PyObject_IsInstance(self.as_ptr(), ty.as_ptr()) };
1247        err::error_on_negative(self.py(), result)?;
1248        Ok(result == 1)
1249    }
1250
1251    #[inline]
1252    fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool {
1253        self.get_type().is(ty)
1254    }
1255
1256    #[inline]
1257    fn is_instance_of<T: PyTypeCheck>(&self) -> bool {
1258        T::type_check(self)
1259    }
1260
1261    #[inline]
1262    fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool {
1263        T::is_exact_type_of(self)
1264    }
1265
1266    fn contains<V>(&self, value: V) -> PyResult<bool>
1267    where
1268        V: IntoPyObject<'py>,
1269    {
1270        let py = self.py();
1271        let value = value.into_pyobject_or_pyerr(py)?;
1272        match unsafe { ffi::PySequence_Contains(self.as_ptr(), value.as_ptr()) } {
1273            0 => Ok(false),
1274            1 => Ok(true),
1275            _ => Err(PyErr::fetch(py)),
1276        }
1277    }
1278
1279    fn py_super(&self) -> PyResult<Bound<'py, PySuper>> {
1280        PySuper::new(&self.get_type(), self)
1281    }
1282}
1283
1284impl<'py> Bound<'py, PyAny> {
1285    /// Retrieve an attribute value, skipping the instance dictionary during the lookup but still
1286    /// binding the object to the instance.
1287    ///
1288    /// This is useful when trying to resolve Python's "magic" methods like `__getitem__`, which
1289    /// are looked up starting from the type object.  This returns an `Option` as it is not
1290    /// typically a direct error for the special lookup to fail, as magic methods are optional in
1291    /// many situations in which they might be called.
1292    ///
1293    /// To avoid repeated temporary allocations of Python strings, the [`intern!`] macro can be used
1294    /// to intern `attr_name`.
1295    #[allow(dead_code, reason = "currently only used with num-complex + abi3")]
1296    pub(crate) fn lookup_special<N>(&self, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>
1297    where
1298        N: IntoPyObject<'py, Target = PyString>,
1299    {
1300        let py = self.py();
1301        let self_type = self.get_type();
1302        let attr = if let Ok(attr) = self_type.getattr(attr_name) {
1303            attr
1304        } else {
1305            return Ok(None);
1306        };
1307
1308        // Manually resolve descriptor protocol. (Faster than going through Python.)
1309        if let Some(descr_get) = attr.get_type().get_slot(TP_DESCR_GET) {
1310            // attribute is a descriptor, resolve it
1311            unsafe {
1312                descr_get(attr.as_ptr(), self.as_ptr(), self_type.as_ptr())
1313                    .assume_owned_or_err(py)
1314                    .map(Some)
1315            }
1316        } else {
1317            Ok(Some(attr))
1318        }
1319    }
1320
1321    #[inline]
1322    pub(crate) fn _get_refcnt(&self) -> isize {
1323        unsafe { ffi::Py_REFCNT(self.as_ptr()) }
1324    }
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329    use crate::platform::prelude::*;
1330    use crate::{
1331        Bound, BoundObject, IntoPyObject, PyTypeInfo, Python,
1332        basic::CompareOp,
1333        test_utils::generate_unique_module_name,
1334        types::{IntoPyDict, PyAny, PyAnyMethods, PyBool, PyInt, PyList, PyModule, PyTypeMethods},
1335    };
1336    use core::fmt::Debug;
1337    use pyo3_ffi::c_str;
1338
1339    #[test]
1340    fn test_lookup_special() {
1341        Python::attach(|py| {
1342            let module = PyModule::from_code(
1343                py,
1344                cr#"
1345class CustomCallable:
1346    def __call__(self):
1347        return 1
1348
1349class SimpleInt:
1350    def __int__(self):
1351        return 1
1352
1353class InheritedInt(SimpleInt): pass
1354
1355class NoInt: pass
1356
1357class NoDescriptorInt:
1358    __int__ = CustomCallable()
1359
1360class InstanceOverrideInt:
1361    def __int__(self):
1362        return 1
1363instance_override = InstanceOverrideInt()
1364instance_override.__int__ = lambda self: 2
1365
1366class ErrorInDescriptorInt:
1367    @property
1368    def __int__(self):
1369        raise ValueError("uh-oh!")
1370
1371class NonHeapNonDescriptorInt:
1372    # A static-typed callable that doesn't implement `__get__`.  These are pretty hard to come by.
1373    __int__ = int
1374                "#,
1375                c"test.py",
1376                &generate_unique_module_name("test"),
1377            )
1378            .unwrap();
1379
1380            let int = crate::intern!(py, "__int__");
1381            let eval_int =
1382                |obj: Bound<'_, PyAny>| obj.lookup_special(int)?.unwrap().call0()?.extract::<u32>();
1383
1384            let simple = module.getattr("SimpleInt").unwrap().call0().unwrap();
1385            assert_eq!(eval_int(simple).unwrap(), 1);
1386            let inherited = module.getattr("InheritedInt").unwrap().call0().unwrap();
1387            assert_eq!(eval_int(inherited).unwrap(), 1);
1388            let no_descriptor = module.getattr("NoDescriptorInt").unwrap().call0().unwrap();
1389            assert_eq!(eval_int(no_descriptor).unwrap(), 1);
1390            let missing = module.getattr("NoInt").unwrap().call0().unwrap();
1391            assert!(missing.lookup_special(int).unwrap().is_none());
1392            // Note the instance override should _not_ call the instance method that returns 2,
1393            // because that's not how special lookups are meant to work.
1394            let instance_override = module.getattr("instance_override").unwrap();
1395            assert_eq!(eval_int(instance_override).unwrap(), 1);
1396            let descriptor_error = module
1397                .getattr("ErrorInDescriptorInt")
1398                .unwrap()
1399                .call0()
1400                .unwrap();
1401            assert!(descriptor_error.lookup_special(int).is_err());
1402            let nonheap_nondescriptor = module
1403                .getattr("NonHeapNonDescriptorInt")
1404                .unwrap()
1405                .call0()
1406                .unwrap();
1407            assert_eq!(eval_int(nonheap_nondescriptor).unwrap(), 0);
1408        })
1409    }
1410
1411    #[test]
1412    fn test_getattr_opt() {
1413        Python::attach(|py| {
1414            let module = PyModule::from_code(
1415                py,
1416                cr#"
1417class Test:
1418    class_str_attribute = "class_string"
1419
1420    @property
1421    def error(self):
1422        raise ValueError("This is an intentional error")
1423                "#,
1424                c"test.py",
1425                &generate_unique_module_name("test"),
1426            )
1427            .unwrap();
1428
1429            // Get the class Test
1430            let class_test = module.getattr_opt("Test").unwrap().unwrap();
1431
1432            // Test attribute that exist
1433            let cls_attr_str = class_test
1434                .getattr_opt("class_str_attribute")
1435                .unwrap()
1436                .unwrap();
1437            assert_eq!(cls_attr_str.extract::<String>().unwrap(), "class_string");
1438
1439            // Test non-existent attribute
1440            let do_not_exist = class_test.getattr_opt("doNotExist").unwrap();
1441            assert!(do_not_exist.is_none());
1442
1443            // Test error attribute
1444            let instance = class_test.call0().unwrap();
1445            let error = instance.getattr_opt("error");
1446            assert!(error.is_err());
1447            assert!(
1448                error
1449                    .unwrap_err()
1450                    .to_string()
1451                    .contains("This is an intentional error")
1452            );
1453        });
1454    }
1455
1456    #[test]
1457    fn test_getattr_opt_attribute_error_subclass() {
1458        Python::attach(|py| {
1459            let module = PyModule::from_code(
1460                py,
1461                cr#"
1462class CustomAttrError(AttributeError):
1463    pass
1464
1465class Obj:
1466    @property
1467    def missing(self):
1468        raise CustomAttrError("not here")
1469                "#,
1470                c"test.py",
1471                &generate_unique_module_name("test"),
1472            )
1473            .unwrap();
1474
1475            let obj = module.getattr("Obj").unwrap().call0().unwrap();
1476
1477            // An AttributeError subclass should be treated as "attribute not found"
1478            let result = obj.getattr_opt("missing").unwrap();
1479            assert!(result.is_none());
1480        });
1481    }
1482
1483    #[test]
1484    fn test_call_for_non_existing_method() {
1485        Python::attach(|py| {
1486            let a = py.eval(c"42", None, None).unwrap();
1487            a.call_method0("__str__").unwrap(); // ok
1488            assert!(a.call_method("nonexistent_method", (1,), None).is_err());
1489            assert!(a.call_method0("nonexistent_method").is_err());
1490            assert!(a.call_method1("nonexistent_method", (1,)).is_err());
1491        });
1492    }
1493
1494    #[test]
1495    fn test_call_with_kwargs() {
1496        Python::attach(|py| {
1497            let list = vec![3, 6, 5, 4, 7].into_pyobject(py).unwrap();
1498            let dict = vec![("reverse", true)].into_py_dict(py).unwrap();
1499            list.call_method("sort", (), Some(&dict)).unwrap();
1500            assert_eq!(list.extract::<Vec<i32>>().unwrap(), vec![7, 6, 5, 4, 3]);
1501        });
1502    }
1503
1504    #[test]
1505    fn test_call_method0() {
1506        Python::attach(|py| {
1507            let module = PyModule::from_code(
1508                py,
1509                cr#"
1510class SimpleClass:
1511    def foo(self):
1512        return 42
1513"#,
1514                c_str!(file!()),
1515                &generate_unique_module_name("test_module"),
1516            )
1517            .expect("module creation failed");
1518
1519            let simple_class = module.getattr("SimpleClass").unwrap().call0().unwrap();
1520            assert_eq!(
1521                simple_class
1522                    .call_method0("foo")
1523                    .unwrap()
1524                    .extract::<u32>()
1525                    .unwrap(),
1526                42
1527            );
1528        })
1529    }
1530
1531    #[test]
1532    fn test_type() {
1533        Python::attach(|py| {
1534            let obj = py.eval(c"42", None, None).unwrap();
1535            assert_eq!(obj.get_type().as_type_ptr(), obj.get_type_ptr());
1536        });
1537    }
1538
1539    #[test]
1540    fn test_dir() {
1541        Python::attach(|py| {
1542            let obj = py.eval(c"42", None, None).unwrap();
1543            let dir = py
1544                .eval(c"dir(42)", None, None)
1545                .unwrap()
1546                .cast_into::<PyList>()
1547                .unwrap();
1548            let a = obj
1549                .dir()
1550                .unwrap()
1551                .into_iter()
1552                .map(|x| x.extract::<String>().unwrap());
1553            let b = dir.into_iter().map(|x| x.extract::<String>().unwrap());
1554            assert!(a.eq(b));
1555        });
1556    }
1557
1558    #[test]
1559    fn test_hasattr() {
1560        Python::attach(|py| {
1561            let x = 5i32.into_pyobject(py).unwrap();
1562            assert!(x.is_instance_of::<PyInt>());
1563
1564            assert!(x.hasattr("to_bytes").unwrap());
1565            assert!(!x.hasattr("bbbbbbytes").unwrap());
1566        })
1567    }
1568
1569    #[cfg(feature = "macros")]
1570    #[test]
1571    fn test_hasattr_error() {
1572        use crate::exceptions::PyValueError;
1573        use crate::prelude::*;
1574
1575        #[pyclass(crate = "crate")]
1576        struct GetattrFail;
1577
1578        #[pymethods(crate = "crate")]
1579        impl GetattrFail {
1580            fn __getattr__(&self, attr: Py<PyAny>) -> PyResult<Py<PyAny>> {
1581                Err(PyValueError::new_err(attr))
1582            }
1583        }
1584
1585        Python::attach(|py| {
1586            let obj = Py::new(py, GetattrFail).unwrap();
1587            let obj = obj.bind(py).as_any();
1588
1589            assert!(
1590                obj.hasattr("foo")
1591                    .unwrap_err()
1592                    .is_instance_of::<PyValueError>(py)
1593            );
1594        })
1595    }
1596
1597    #[test]
1598    fn test_nan_eq() {
1599        Python::attach(|py| {
1600            let nan = py.eval(c"float('nan')", None, None).unwrap();
1601            assert!(nan.compare(&nan).is_err());
1602        });
1603    }
1604
1605    #[test]
1606    fn test_any_is_instance_of() {
1607        Python::attach(|py| {
1608            let x = 5i32.into_pyobject(py).unwrap();
1609            assert!(x.is_instance_of::<PyInt>());
1610
1611            let l = vec![&x, &x].into_pyobject(py).unwrap();
1612            assert!(l.is_instance_of::<PyList>());
1613        });
1614    }
1615
1616    #[test]
1617    fn test_any_is_instance() {
1618        Python::attach(|py| {
1619            let l = vec![1i8, 2].into_pyobject(py).unwrap();
1620            assert!(l.is_instance(&py.get_type::<PyList>()).unwrap());
1621        });
1622    }
1623
1624    #[test]
1625    fn test_any_is_exact_instance_of() {
1626        Python::attach(|py| {
1627            let x = 5i32.into_pyobject(py).unwrap();
1628            assert!(x.is_exact_instance_of::<PyInt>());
1629
1630            let t = PyBool::new(py, true);
1631            assert!(t.is_instance_of::<PyInt>());
1632            assert!(!t.is_exact_instance_of::<PyInt>());
1633            assert!(t.is_exact_instance_of::<PyBool>());
1634
1635            let l = vec![&x, &x].into_pyobject(py).unwrap();
1636            assert!(l.is_exact_instance_of::<PyList>());
1637        });
1638    }
1639
1640    #[test]
1641    fn test_any_is_exact_instance() {
1642        Python::attach(|py| {
1643            let t = PyBool::new(py, true);
1644            assert!(t.is_instance(&py.get_type::<PyInt>()).unwrap());
1645            assert!(!t.is_exact_instance(&py.get_type::<PyInt>()));
1646            assert!(t.is_exact_instance(&py.get_type::<PyBool>()));
1647        });
1648    }
1649
1650    #[test]
1651    fn test_any_contains() {
1652        Python::attach(|py| {
1653            let v: Vec<i32> = vec![1, 1, 2, 3, 5, 8];
1654            let ob = v.into_pyobject(py).unwrap();
1655
1656            let bad_needle = 7i32.into_pyobject(py).unwrap();
1657            assert!(!ob.contains(&bad_needle).unwrap());
1658
1659            let good_needle = 8i32.into_pyobject(py).unwrap();
1660            assert!(ob.contains(&good_needle).unwrap());
1661
1662            let type_coerced_needle = 8f32.into_pyobject(py).unwrap();
1663            assert!(ob.contains(&type_coerced_needle).unwrap());
1664
1665            let n: u32 = 42;
1666            let bad_haystack = n.into_pyobject(py).unwrap();
1667            let irrelevant_needle = 0i32.into_pyobject(py).unwrap();
1668            assert!(bad_haystack.contains(&irrelevant_needle).is_err());
1669        });
1670    }
1671
1672    // This is intentionally not a test, it's a generic function used by the tests below.
1673    fn test_eq_methods_generic<'a, T>(list: &'a [T])
1674    where
1675        T: PartialEq + PartialOrd,
1676        for<'py> &'a T: IntoPyObject<'py>,
1677        for<'py> <&'a T as IntoPyObject<'py>>::Error: Debug,
1678    {
1679        Python::attach(|py| {
1680            for a in list {
1681                for b in list {
1682                    let a_py = a.into_pyobject(py).unwrap().into_any().into_bound();
1683                    let b_py = b.into_pyobject(py).unwrap().into_any().into_bound();
1684
1685                    assert_eq!(
1686                        a.lt(b),
1687                        a_py.lt(&b_py).unwrap(),
1688                        "{} < {} should be {}.",
1689                        a_py,
1690                        b_py,
1691                        a.lt(b)
1692                    );
1693                    assert_eq!(
1694                        a.le(b),
1695                        a_py.le(&b_py).unwrap(),
1696                        "{} <= {} should be {}.",
1697                        a_py,
1698                        b_py,
1699                        a.le(b)
1700                    );
1701                    assert_eq!(
1702                        a.eq(b),
1703                        a_py.eq(&b_py).unwrap(),
1704                        "{} == {} should be {}.",
1705                        a_py,
1706                        b_py,
1707                        a.eq(b)
1708                    );
1709                    assert_eq!(
1710                        a.ne(b),
1711                        a_py.ne(&b_py).unwrap(),
1712                        "{} != {} should be {}.",
1713                        a_py,
1714                        b_py,
1715                        a.ne(b)
1716                    );
1717                    assert_eq!(
1718                        a.gt(b),
1719                        a_py.gt(&b_py).unwrap(),
1720                        "{} > {} should be {}.",
1721                        a_py,
1722                        b_py,
1723                        a.gt(b)
1724                    );
1725                    assert_eq!(
1726                        a.ge(b),
1727                        a_py.ge(&b_py).unwrap(),
1728                        "{} >= {} should be {}.",
1729                        a_py,
1730                        b_py,
1731                        a.ge(b)
1732                    );
1733                }
1734            }
1735        });
1736    }
1737
1738    #[test]
1739    fn test_eq_methods_integers() {
1740        let ints = [-4, -4, 1, 2, 0, -100, 1_000_000];
1741        test_eq_methods_generic::<i32>(&ints);
1742    }
1743
1744    #[test]
1745    fn test_eq_methods_strings() {
1746        let strings = ["Let's", "test", "some", "eq", "methods"];
1747        test_eq_methods_generic::<&str>(&strings);
1748    }
1749
1750    #[test]
1751    fn test_eq_methods_floats() {
1752        let floats = [
1753            -1.0,
1754            2.5,
1755            0.0,
1756            3.0,
1757            core::f64::consts::PI,
1758            10.0,
1759            10.0 / 3.0,
1760            -1_000_000.0,
1761        ];
1762        test_eq_methods_generic::<f64>(&floats);
1763    }
1764
1765    #[test]
1766    fn test_eq_methods_bools() {
1767        let bools = [true, false];
1768        test_eq_methods_generic::<bool>(&bools);
1769    }
1770
1771    #[test]
1772    fn test_rich_compare_type_error() {
1773        Python::attach(|py| {
1774            let py_int = 1i32.into_pyobject(py).unwrap();
1775            let py_str = "1".into_pyobject(py).unwrap();
1776
1777            assert!(py_int.rich_compare(&py_str, CompareOp::Lt).is_err());
1778            assert!(
1779                !py_int
1780                    .rich_compare(py_str, CompareOp::Eq)
1781                    .unwrap()
1782                    .is_truthy()
1783                    .unwrap()
1784            );
1785        })
1786    }
1787
1788    #[test]
1789    fn test_is_callable() {
1790        Python::attach(|py| {
1791            assert!(PyList::type_object(py).is_callable());
1792
1793            let not_callable = 5i32.into_pyobject(py).unwrap();
1794            assert!(!not_callable.is_callable());
1795        });
1796    }
1797
1798    #[test]
1799    fn test_is_empty() {
1800        Python::attach(|py| {
1801            let empty_list = PyList::empty(py).into_any();
1802            assert!(empty_list.is_empty().unwrap());
1803
1804            let list = PyList::new(py, vec![1, 2, 3]).unwrap().into_any();
1805            assert!(!list.is_empty().unwrap());
1806
1807            let not_container = 5i32.into_pyobject(py).unwrap();
1808            assert!(not_container.is_empty().is_err());
1809        });
1810    }
1811
1812    #[cfg(feature = "macros")]
1813    #[test]
1814    fn test_fallible_dir() {
1815        use crate::exceptions::PyValueError;
1816        use crate::prelude::*;
1817
1818        #[pyclass(crate = "crate")]
1819        struct DirFail;
1820
1821        #[pymethods(crate = "crate")]
1822        impl DirFail {
1823            fn __dir__(&self) -> PyResult<Py<PyAny>> {
1824                Err(PyValueError::new_err("uh-oh!"))
1825            }
1826        }
1827
1828        Python::attach(|py| {
1829            let obj = Bound::new(py, DirFail).unwrap();
1830            assert!(obj.dir().unwrap_err().is_instance_of::<PyValueError>(py));
1831        })
1832    }
1833}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here