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#[doc = concat!("[the guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html#concrete-python-types)")]
33#[repr(transparent)]
35pub struct PyAny(UnsafeCell<ffi::PyObject>);
36
37#[allow(non_snake_case)]
38fn PyObject_Check(_: *mut ffi::PyObject) -> c_int {
40 1
41}
42
43#[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#[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#[doc(alias = "PyAny")]
91pub trait PyAnyMethods<'py>: crate::sealed::Sealed {
92 fn is<T: AsRef<Py<PyAny>>>(&self, other: T) -> bool;
97
98 fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
121 where
122 N: IntoPyObject<'py, Target = PyString>;
123
124 fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
147 where
148 N: IntoPyObject<'py, Target = PyString>;
149
150 fn getattr_opt<N>(&self, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>
179 where
180 N: IntoPyObject<'py, Target = PyString>;
181
182 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 fn delattr<N>(&self, attr_name: N) -> PyResult<()>
216 where
217 N: IntoPyObject<'py, Target = PyString>;
218
219 fn compare<O>(&self, other: O) -> PyResult<Ordering>
266 where
267 O: IntoPyObject<'py>;
268
269 fn rich_compare<O>(&self, other: O, compare_op: CompareOp) -> PyResult<Bound<'py, PyAny>>
303 where
304 O: IntoPyObject<'py>;
305
306 fn neg(&self) -> PyResult<Bound<'py, PyAny>>;
310
311 fn pos(&self) -> PyResult<Bound<'py, PyAny>>;
315
316 fn abs(&self) -> PyResult<Bound<'py, PyAny>>;
320
321 fn bitnot(&self) -> PyResult<Bound<'py, PyAny>>;
323
324 fn lt<O>(&self, other: O) -> PyResult<bool>
328 where
329 O: IntoPyObject<'py>;
330
331 fn le<O>(&self, other: O) -> PyResult<bool>
335 where
336 O: IntoPyObject<'py>;
337
338 fn eq<O>(&self, other: O) -> PyResult<bool>
342 where
343 O: IntoPyObject<'py>;
344
345 fn ne<O>(&self, other: O) -> PyResult<bool>
349 where
350 O: IntoPyObject<'py>;
351
352 fn gt<O>(&self, other: O) -> PyResult<bool>
356 where
357 O: IntoPyObject<'py>;
358
359 fn ge<O>(&self, other: O) -> PyResult<bool>
363 where
364 O: IntoPyObject<'py>;
365
366 fn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
368 where
369 O: IntoPyObject<'py>;
370
371 fn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
373 where
374 O: IntoPyObject<'py>;
375
376 fn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
378 where
379 O: IntoPyObject<'py>;
380
381 fn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
383 where
384 O: IntoPyObject<'py>;
385
386 fn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
388 where
389 O: IntoPyObject<'py>;
390
391 fn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
393 where
394 O: IntoPyObject<'py>;
395
396 fn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
398 where
399 O: IntoPyObject<'py>;
400
401 fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
403 where
404 O: IntoPyObject<'py>;
405
406 fn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
408 where
409 O: IntoPyObject<'py>;
410
411 fn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
413 where
414 O: IntoPyObject<'py>;
415
416 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 fn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
425 where
426 O: IntoPyObject<'py>;
427
428 fn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
430 where
431 O: IntoPyObject<'py>;
432
433 fn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
435 where
436 O: IntoPyObject<'py>;
437
438 fn is_callable(&self) -> bool;
466
467 fn call<A>(&self, args: A, kwargs: Option<&Bound<'py, PyDict>>) -> PyResult<Bound<'py, PyAny>>
500 where
501 A: PyCallArgs<'py>;
502
503 fn call0(&self) -> PyResult<Bound<'py, PyAny>>;
524
525 fn call1<A>(&self, args: A) -> PyResult<Bound<'py, PyAny>>
555 where
556 A: PyCallArgs<'py>;
557
558 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 fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
639 where
640 N: IntoPyObject<'py, Target = PyString>;
641
642 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 fn is_truthy(&self) -> PyResult<bool>;
685
686 fn is_none(&self) -> bool;
690
691 fn is_empty(&self) -> PyResult<bool>;
695
696 fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>
700 where
701 K: IntoPyObject<'py>;
702
703 fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
707 where
708 K: IntoPyObject<'py>,
709 V: IntoPyObject<'py>;
710
711 fn del_item<K>(&self, key: K) -> PyResult<()>
715 where
716 K: IntoPyObject<'py>;
717
718 fn try_iter(&self) -> PyResult<Bound<'py, PyIterator>>;
743
744 fn get_type(&self) -> Bound<'py, PyType>;
746
747 fn get_type_ptr(&self) -> *mut ffi::PyTypeObject;
749
750 fn extract<'a, T>(&'a self) -> Result<T, T::Error>
754 where
755 T: FromPyObject<'a, 'py>;
756
757 fn repr(&self) -> PyResult<Bound<'py, PyString>>;
761
762 fn str(&self) -> PyResult<Bound<'py, PyString>>;
766
767 fn hash(&self) -> PyResult<isize>;
771
772 fn len(&self) -> PyResult<usize>;
776
777 fn dir(&self) -> PyResult<Bound<'py, PyList>>;
781
782 fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>;
786
787 fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool;
791
792 fn is_instance_of<T: PyTypeCheck>(&self) -> bool;
797
798 fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool;
803
804 fn contains<V>(&self, value: V) -> PyResult<bool>
808 where
809 V: IntoPyObject<'py>;
810
811 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 1 => Ok(Some(unsafe { resp_ptr.assume_owned_unchecked(py) })),
871 0 => Ok(None),
873 _ => 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 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 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 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 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 #[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 if let Some(descr_get) = attr.get_type().get_slot(TP_DESCR_GET) {
1310 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 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 let class_test = module.getattr_opt("Test").unwrap().unwrap();
1431
1432 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 let do_not_exist = class_test.getattr_opt("doNotExist").unwrap();
1441 assert!(do_not_exist.is_none());
1442
1443 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 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(); 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 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}