Trait PyAnyMethods
pub trait PyAnyMethods<'py>: Sealed {
Show 68 methods
// Required methods
fn is<T>(&self, other: &T) -> bool
where T: AsPyPointer;
fn hasattr<N>(&self, attr_name: N) -> Result<bool, PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>;
fn getattr<N>(&self, attr_name: N) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>;
fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>,
V: IntoPyObject<'py>;
fn delattr<N>(&self, attr_name: N) -> Result<(), PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>;
fn compare<O>(&self, other: O) -> Result<Ordering, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn neg(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ;
fn pos(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ;
fn abs(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ;
fn bitnot(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ;
fn lt<O>(&self, other: O) -> Result<bool, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn le<O>(&self, other: O) -> Result<bool, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn eq<O>(&self, other: O) -> Result<bool, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn ne<O>(&self, other: O) -> Result<bool, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn gt<O>(&self, other: O) -> Result<bool, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn ge<O>(&self, other: O) -> Result<bool, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn add<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn sub<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn mul<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn matmul<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn div<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn floor_div<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn rem<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn divmod<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn lshift<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn rshift<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn pow<O1, O2>(
&self,
other: O1,
modulus: O2,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O1: IntoPyObject<'py>,
O2: IntoPyObject<'py>;
fn bitand<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn bitor<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn bitxor<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where O: IntoPyObject<'py>;
fn is_callable(&self) -> bool;
fn call<A>(
&self,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where A: IntoPyObject<'py, Target = PyTuple>;
fn call0(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ;
fn call1<A>(&self, args: A) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where A: IntoPyObject<'py, Target = PyTuple>;
fn call_method<N, A>(
&self,
name: N,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>,
A: IntoPyObject<'py, Target = PyTuple>;
fn call_method0<N>(&self, name: N) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>;
fn call_method1<N, A>(
&self,
name: N,
args: A,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where N: IntoPyObject<'py, Target = PyString>,
A: IntoPyObject<'py, Target = PyTuple>;
fn is_truthy(&self) -> Result<bool, PyErr> ⓘ;
fn is_none(&self) -> bool;
fn is_ellipsis(&self) -> bool;
fn is_empty(&self) -> Result<bool, PyErr> ⓘ;
fn get_item<K>(&self, key: K) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
where K: IntoPyObject<'py>;
fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> ⓘ
where K: IntoPyObject<'py>,
V: IntoPyObject<'py>;
fn del_item<K>(&self, key: K) -> Result<(), PyErr> ⓘ
where K: IntoPyObject<'py>;
fn try_iter(&self) -> Result<Bound<'py, PyIterator>, PyErr> ⓘ;
fn iter(&self) -> Result<Bound<'py, PyIterator>, PyErr> ⓘ;
fn get_type(&self) -> Bound<'py, PyType>;
fn get_type_ptr(&self) -> *mut PyTypeObject;
fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> ⓘ
where T: PyTypeCheck;
fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> ⓘ
where T: PyTypeCheck;
fn downcast_exact<T>(
&self,
) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> ⓘ
where T: PyTypeInfo;
fn downcast_into_exact<T>(
self,
) -> Result<Bound<'py, T>, DowncastIntoError<'py>> ⓘ
where T: PyTypeInfo;
unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T>;
unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T>;
fn extract<'a, T>(&'a self) -> Result<T, PyErr> ⓘ
where T: FromPyObjectBound<'a, 'py>;
fn get_refcnt(&self) -> isize ⓘ;
fn repr(&self) -> Result<Bound<'py, PyString>, PyErr> ⓘ;
fn str(&self) -> Result<Bound<'py, PyString>, PyErr> ⓘ;
fn hash(&self) -> Result<isize, PyErr> ⓘ;
fn len(&self) -> Result<usize, PyErr> ⓘ;
fn dir(&self) -> Result<Bound<'py, PyList>, PyErr> ⓘ;
fn is_instance(&self, ty: &Bound<'py, PyAny>) -> Result<bool, PyErr> ⓘ;
fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool;
fn is_instance_of<T>(&self) -> bool
where T: PyTypeInfo;
fn is_exact_instance_of<T>(&self) -> bool
where T: PyTypeInfo;
fn contains<V>(&self, value: V) -> Result<bool, PyErr> ⓘ
where V: IntoPyObject<'py>;
fn py_super(&self) -> Result<Bound<'py, PySuper>, PyErr> ⓘ;
}
dep_pyo3
and std
only.Expand description
This trait represents the Python APIs which are usable on all Python objects.
It is recommended you import this trait via use pyo3::prelude::*
rather than
by importing this trait directly.
Required Methods§
fn is<T>(&self, other: &T) -> boolwhere
T: AsPyPointer,
fn is<T>(&self, other: &T) -> boolwhere
T: AsPyPointer,
Returns whether self
and other
point to the same object. To compare
the equality of two objects (the ==
operator), use eq
.
This is equivalent to the Python expression self is other
.
fn hasattr<N>(&self, attr_name: N) -> Result<bool, PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
fn hasattr<N>(&self, attr_name: N) -> Result<bool, PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
Determines whether this object has the given attribute.
This is equivalent to the Python expression hasattr(self, attr_name)
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern attr_name
.
§Example: intern!
ing the attribute name
#[pyfunction]
fn has_version(sys: &Bound<'_, PyModule>) -> PyResult<bool> {
sys.hasattr(intern!(sys.py(), "version"))
}
fn getattr<N>(&self, attr_name: N) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
fn getattr<N>(&self, attr_name: N) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
Retrieves an attribute value.
This is equivalent to the Python expression self.attr_name
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern attr_name
.
§Example: intern!
ing the attribute name
#[pyfunction]
fn version<'py>(sys: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyAny>> {
sys.getattr(intern!(sys.py(), "version"))
}
fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> ⓘ
fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> ⓘ
Sets an attribute value.
This is equivalent to the Python expression self.attr_name = value
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern name
.
§Example: intern!
ing the attribute name
#[pyfunction]
fn set_answer(ob: &Bound<'_, PyAny>) -> PyResult<()> {
ob.setattr(intern!(ob.py(), "answer"), 42)
}
fn delattr<N>(&self, attr_name: N) -> Result<(), PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
fn delattr<N>(&self, attr_name: N) -> Result<(), PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
Deletes an attribute.
This is equivalent to the Python statement del self.attr_name
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern attr_name
.
fn compare<O>(&self, other: O) -> Result<Ordering, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn compare<O>(&self, other: O) -> Result<Ordering, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Returns an Ordering
between self
and other
.
This is equivalent to the following Python code:
if self == other:
return Equal
elif a < b:
return Less
elif a > b:
return Greater
else:
raise TypeError("PyAny::compare(): All comparisons returned false")
§Examples
use pyo3::prelude::*;
use pyo3::types::PyFloat;
use std::cmp::Ordering;
Python::with_gil(|py| -> PyResult<()> {
let a = PyFloat::new(py, 0_f64);
let b = PyFloat::new(py, 42_f64);
assert_eq!(a.compare(b)?, Ordering::Less);
Ok(())
})?;
It will return PyErr
for values that cannot be compared:
use pyo3::prelude::*;
use pyo3::types::{PyFloat, PyString};
Python::with_gil(|py| -> PyResult<()> {
let a = PyFloat::new(py, 0_f64);
let b = PyString::new(py, "zero");
assert!(a.compare(b).is_err());
Ok(())
})?;
fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether two Python objects obey a given CompareOp
.
lt
, le
, eq
, ne
,
gt
and ge
are the specialized versions
of this function.
Depending on the value of compare_op
, this is equivalent to one of the
following Python expressions:
compare_op | Python expression |
---|---|
CompareOp::Eq | self == other |
CompareOp::Ne | self != other |
CompareOp::Lt | self < other |
CompareOp::Le | self <= other |
CompareOp::Gt | self > other |
CompareOp::Ge | self >= other |
§Examples
use pyo3::class::basic::CompareOp;
use pyo3::prelude::*;
Python::with_gil(|py| -> PyResult<()> {
let a = 0_u8.into_pyobject(py)?;
let b = 42_u8.into_pyobject(py)?;
assert!(a.rich_compare(b, CompareOp::Le)?.is_truthy()?);
Ok(())
})?;
fn neg(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn neg(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
Computes the negative of self.
Equivalent to the Python expression -self
.
fn pos(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn pos(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
Computes the positive of self.
Equivalent to the Python expression +self
.
fn abs(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn abs(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
Computes the absolute of self.
Equivalent to the Python expression abs(self)
.
fn lt<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn lt<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether this object is less than another.
This is equivalent to the Python expression self < other
.
fn le<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn le<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether this object is less than or equal to another.
This is equivalent to the Python expression self <= other
.
fn eq<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn eq<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether this object is equal to another.
This is equivalent to the Python expression self == other
.
fn ne<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn ne<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether this object is not equal to another.
This is equivalent to the Python expression self != other
.
fn gt<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn gt<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether this object is greater than another.
This is equivalent to the Python expression self > other
.
fn ge<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn ge<O>(&self, other: O) -> Result<bool, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Tests whether this object is greater than or equal to another.
This is equivalent to the Python expression self >= other
.
fn add<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn add<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self + other
.
fn sub<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn sub<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self - other
.
fn mul<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn mul<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self * other
.
fn matmul<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn matmul<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self @ other
.
fn div<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn div<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self / other
.
fn floor_div<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn floor_div<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self // other
.
fn rem<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn rem<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self % other
.
fn divmod<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn divmod<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes divmod(self, other)
.
fn lshift<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn lshift<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self << other
.
fn rshift<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn rshift<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self >> other
.
fn pow<O1, O2>(
&self,
other: O1,
modulus: O2,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O1: IntoPyObject<'py>,
O2: IntoPyObject<'py>,
fn pow<O1, O2>(
&self,
other: O1,
modulus: O2,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O1: IntoPyObject<'py>,
O2: IntoPyObject<'py>,
Computes self ** other % modulus
(pow(self, other, modulus)
).
py.None()
may be passed for the modulus
.
fn bitand<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn bitand<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self & other
.
fn bitor<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn bitor<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self | other
.
fn bitxor<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
fn bitxor<O>(&self, other: O) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
O: IntoPyObject<'py>,
Computes self ^ other
.
fn is_callable(&self) -> bool
fn is_callable(&self) -> bool
Determines whether this object appears callable.
This is equivalent to Python’s callable()
function.
§Examples
use pyo3::prelude::*;
Python::with_gil(|py| -> PyResult<()> {
let builtins = PyModule::import(py, "builtins")?;
let print = builtins.getattr("print")?;
assert!(print.is_callable());
Ok(())
})?;
This is equivalent to the Python statement assert callable(print)
.
Note that unless an API needs to distinguish between callable and non-callable objects, there is no point in checking for callability. Instead, it is better to just do the call and handle potential exceptions.
fn call<A>(
&self,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
A: IntoPyObject<'py, Target = PyTuple>,
fn call<A>(
&self,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
A: IntoPyObject<'py, Target = PyTuple>,
Calls the object.
This is equivalent to the Python expression self(*args, **kwargs)
.
§Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3_ffi::c_str;
use std::ffi::CStr;
const CODE: &CStr = c_str!(r#"
def function(*args, **kwargs):
assert args == ("hello",)
assert kwargs == {"cruel": "world"}
return "called with args and kwargs"
"#);
Python::with_gil(|py| {
let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?;
let fun = module.getattr("function")?;
let args = ("hello",);
let kwargs = PyDict::new(py);
kwargs.set_item("cruel", "world")?;
let result = fun.call(args, Some(&kwargs))?;
assert_eq!(result.extract::<String>()?, "called with args and kwargs");
Ok(())
})
fn call0(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn call0(&self) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
Calls the object without arguments.
This is equivalent to the Python expression self()
.
§Examples
use pyo3::prelude::*;
Python::with_gil(|py| -> PyResult<()> {
let module = PyModule::import(py, "builtins")?;
let help = module.getattr("help")?;
help.call0()?;
Ok(())
})?;
This is equivalent to the Python expression help()
.
fn call1<A>(&self, args: A) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
A: IntoPyObject<'py, Target = PyTuple>,
fn call1<A>(&self, args: A) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
A: IntoPyObject<'py, Target = PyTuple>,
Calls the object with only positional arguments.
This is equivalent to the Python expression self(*args)
.
§Examples
use pyo3::prelude::*;
use pyo3_ffi::c_str;
use std::ffi::CStr;
const CODE: &CStr = c_str!(r#"
def function(*args, **kwargs):
assert args == ("hello",)
assert kwargs == {}
return "called with args"
"#);
Python::with_gil(|py| {
let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?;
let fun = module.getattr("function")?;
let args = ("hello",);
let result = fun.call1(args)?;
assert_eq!(result.extract::<String>()?, "called with args");
Ok(())
})
fn call_method<N, A>(
&self,
name: N,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn call_method<N, A>( &self, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
Calls a method on the object.
This is equivalent to the Python expression self.name(*args, **kwargs)
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern name
.
§Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3_ffi::c_str;
use std::ffi::CStr;
const CODE: &CStr = c_str!(r#"
class A:
def method(self, *args, **kwargs):
assert args == ("hello",)
assert kwargs == {"cruel": "world"}
return "called with args and kwargs"
a = A()
"#);
Python::with_gil(|py| {
let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?;
let instance = module.getattr("a")?;
let args = ("hello",);
let kwargs = PyDict::new(py);
kwargs.set_item("cruel", "world")?;
let result = instance.call_method("method", args, Some(&kwargs))?;
assert_eq!(result.extract::<String>()?, "called with args and kwargs");
Ok(())
})
fn call_method0<N>(&self, name: N) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
fn call_method0<N>(&self, name: N) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
N: IntoPyObject<'py, Target = PyString>,
Calls a method on the object without arguments.
This is equivalent to the Python expression self.name()
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern name
.
§Examples
use pyo3::prelude::*;
use pyo3_ffi::c_str;
use std::ffi::CStr;
const CODE: &CStr = c_str!(r#"
class A:
def method(self, *args, **kwargs):
assert args == ()
assert kwargs == {}
return "called with no arguments"
a = A()
"#);
Python::with_gil(|py| {
let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?;
let instance = module.getattr("a")?;
let result = instance.call_method0("method")?;
assert_eq!(result.extract::<String>()?, "called with no arguments");
Ok(())
})
fn call_method1<N, A>(
&self,
name: N,
args: A,
) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
fn call_method1<N, A>( &self, name: N, args: A, ) -> Result<Bound<'py, PyAny>, PyErr> ⓘ
Calls a method on the object with only positional arguments.
This is equivalent to the Python expression self.name(*args)
.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used
to intern name
.
§Examples
use pyo3::prelude::*;
use pyo3_ffi::c_str;
use std::ffi::CStr;
const CODE: &CStr = c_str!(r#"
class A:
def method(self, *args, **kwargs):
assert args == ("hello",)
assert kwargs == {}
return "called with args"
a = A()
"#);
Python::with_gil(|py| {
let module = PyModule::from_code(py, CODE, c_str!(""), c_str!(""))?;
let instance = module.getattr("a")?;
let args = ("hello",);
let result = instance.call_method1("method", args)?;
assert_eq!(result.extract::<String>()?, "called with args");
Ok(())
})
fn is_truthy(&self) -> Result<bool, PyErr> ⓘ
fn is_truthy(&self) -> Result<bool, PyErr> ⓘ
Returns whether the object is considered to be true.
This is equivalent to the Python expression bool(self)
.
fn is_none(&self) -> bool
fn is_none(&self) -> bool
Returns whether the object is considered to be None.
This is equivalent to the Python expression self is None
.
fn is_ellipsis(&self) -> bool
👎Deprecated since 0.23.0: use .is(py.Ellipsis())
instead
fn is_ellipsis(&self) -> bool
.is(py.Ellipsis())
insteadReturns whether the object is Ellipsis, e.g. ...
.
This is equivalent to the Python expression self is ...
.
fn is_empty(&self) -> Result<bool, PyErr> ⓘ
fn is_empty(&self) -> Result<bool, PyErr> ⓘ
Returns true if the sequence or mapping has a length of 0.
This is equivalent to the Python expression len(self) == 0
.
fn get_item<K>(&self, key: K) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
K: IntoPyObject<'py>,
fn get_item<K>(&self, key: K) -> Result<Bound<'py, PyAny>, PyErr> ⓘwhere
K: IntoPyObject<'py>,
Gets an item from the collection.
This is equivalent to the Python expression self[key]
.
fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> ⓘwhere
K: IntoPyObject<'py>,
V: IntoPyObject<'py>,
fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> ⓘwhere
K: IntoPyObject<'py>,
V: IntoPyObject<'py>,
Sets a collection item value.
This is equivalent to the Python expression self[key] = value
.
fn del_item<K>(&self, key: K) -> Result<(), PyErr> ⓘwhere
K: IntoPyObject<'py>,
fn del_item<K>(&self, key: K) -> Result<(), PyErr> ⓘwhere
K: IntoPyObject<'py>,
Deletes an item from the collection.
This is equivalent to the Python expression del self[key]
.
fn try_iter(&self) -> Result<Bound<'py, PyIterator>, PyErr> ⓘ
fn try_iter(&self) -> Result<Bound<'py, PyIterator>, PyErr> ⓘ
Takes an object and returns an iterator for it. Returns an error if the object is not iterable.
This is typically a new iterator but if the argument is an iterator, this returns itself.
§Example: Checking a Python object for iterability
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyNone};
fn is_iterable(obj: &Bound<'_, PyAny>) -> bool {
match obj.try_iter() {
Ok(_) => true,
Err(_) => false,
}
}
Python::with_gil(|py| {
assert!(is_iterable(&vec![1, 2, 3].into_pyobject(py).unwrap()));
assert!(!is_iterable(&PyNone::get(py)));
});
fn iter(&self) -> Result<Bound<'py, PyIterator>, PyErr> ⓘ
👎Deprecated since 0.23.0: use try_iter
instead
fn iter(&self) -> Result<Bound<'py, PyIterator>, PyErr> ⓘ
try_iter
insteadTakes an object and returns an iterator for it.
This is typically a new iterator but if the argument is an iterator, this returns itself.
fn get_type_ptr(&self) -> *mut PyTypeObject
fn get_type_ptr(&self) -> *mut PyTypeObject
Returns the Python type pointer for this object.
fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> ⓘwhere
T: PyTypeCheck,
fn downcast<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> ⓘwhere
T: PyTypeCheck,
Downcast this PyAny
to a concrete Python type or pyclass.
Note that you can often avoid downcasting yourself by just specifying the desired type in function or method signatures. However, manual downcasting is sometimes necessary.
For extracting a Rust-only type, see PyAny::extract
.
§Example: Downcasting to a specific Python object
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
Python::with_gil(|py| {
let dict = PyDict::new(py);
assert!(dict.is_instance_of::<PyAny>());
let any = dict.as_any();
assert!(any.downcast::<PyDict>().is_ok());
assert!(any.downcast::<PyList>().is_err());
});
§Example: Getting a reference to a pyclass
This is useful if you want to mutate a PyObject
that
might actually be a pyclass.
use pyo3::prelude::*;
#[pyclass]
struct Class {
i: i32,
}
Python::with_gil(|py| {
let class = Py::new(py, Class { i: 0 }).unwrap().into_bound(py).into_any();
let class_bound: &Bound<'_, Class> = class.downcast()?;
class_bound.borrow_mut().i += 1;
// Alternatively you can get a `PyRefMut` directly
let class_ref: PyRefMut<'_, Class> = class.extract()?;
assert_eq!(class_ref.i, 1);
Ok(())
})
fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> ⓘwhere
T: PyTypeCheck,
fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> ⓘwhere
T: PyTypeCheck,
Like downcast
but takes ownership of self
.
In case of an error, it is possible to retrieve self
again via DowncastIntoError::into_inner
.
§Example
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
Python::with_gil(|py| {
let obj: Bound<'_, PyAny> = PyDict::new(py).into_any();
let obj: Bound<'_, PyAny> = match obj.downcast_into::<PyList>() {
Ok(_) => panic!("obj should not be a list"),
Err(err) => err.into_inner(),
};
// obj is a dictionary
assert!(obj.downcast_into::<PyDict>().is_ok());
})
fn downcast_exact<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> ⓘwhere
T: PyTypeInfo,
fn downcast_exact<T>(&self) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>> ⓘwhere
T: PyTypeInfo,
Downcast this PyAny
to a concrete Python type or pyclass (but not a subclass of it).
It is almost always better to use PyAnyMethods::downcast
because it accounts for Python
subtyping. Use this method only when you do not want to allow subtypes.
The advantage of this method over PyAnyMethods::downcast
is that it is faster. The implementation
of downcast_exact
uses the equivalent of the Python expression type(self) is T
, whereas
downcast
uses isinstance(self, T)
.
For extracting a Rust-only type, see PyAny::extract
.
§Example: Downcasting to a specific Python object but not a subtype
use pyo3::prelude::*;
use pyo3::types::{PyBool, PyInt};
Python::with_gil(|py| {
let b = PyBool::new(py, true);
assert!(b.is_instance_of::<PyBool>());
let any: &Bound<'_, PyAny> = b.as_any();
// `bool` is a subtype of `int`, so `downcast` will accept a `bool` as an `int`
// but `downcast_exact` will not.
assert!(any.downcast::<PyInt>().is_ok());
assert!(any.downcast_exact::<PyInt>().is_err());
assert!(any.downcast_exact::<PyBool>().is_ok());
});
fn downcast_into_exact<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> ⓘwhere
T: PyTypeInfo,
fn downcast_into_exact<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>> ⓘwhere
T: PyTypeInfo,
Like downcast_exact
but takes ownership of self
.
unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T>
unsafe fn downcast_unchecked<T>(&self) -> &Bound<'py, T>
Converts this PyAny
to a concrete Python type without checking validity.
§Safety
Callers must ensure that the type is valid or risk type confusion.
unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T>
unsafe fn downcast_into_unchecked<T>(self) -> Bound<'py, T>
Like downcast_unchecked
but takes ownership of self
.
§Safety
Callers must ensure that the type is valid or risk type confusion.
fn extract<'a, T>(&'a self) -> Result<T, PyErr> ⓘwhere
T: FromPyObjectBound<'a, 'py>,
fn extract<'a, T>(&'a self) -> Result<T, PyErr> ⓘwhere
T: FromPyObjectBound<'a, 'py>,
Extracts some type from the Python object.
This is a wrapper function around
FromPyObject::extract_bound()
.
fn get_refcnt(&self) -> isize ⓘ
fn get_refcnt(&self) -> isize ⓘ
Returns the reference count for the Python object.
fn repr(&self) -> Result<Bound<'py, PyString>, PyErr> ⓘ
fn repr(&self) -> Result<Bound<'py, PyString>, PyErr> ⓘ
Computes the “repr” representation of self.
This is equivalent to the Python expression repr(self)
.
fn str(&self) -> Result<Bound<'py, PyString>, PyErr> ⓘ
fn str(&self) -> Result<Bound<'py, PyString>, PyErr> ⓘ
Computes the “str” representation of self.
This is equivalent to the Python expression str(self)
.
fn hash(&self) -> Result<isize, PyErr> ⓘ
fn hash(&self) -> Result<isize, PyErr> ⓘ
Retrieves the hash code of self.
This is equivalent to the Python expression hash(self)
.
fn len(&self) -> Result<usize, PyErr> ⓘ
fn len(&self) -> Result<usize, PyErr> ⓘ
Returns the length of the sequence or mapping.
This is equivalent to the Python expression len(self)
.
fn dir(&self) -> Result<Bound<'py, PyList>, PyErr> ⓘ
fn dir(&self) -> Result<Bound<'py, PyList>, PyErr> ⓘ
Returns the list of attributes of this object.
This is equivalent to the Python expression dir(self)
.
fn is_instance(&self, ty: &Bound<'py, PyAny>) -> Result<bool, PyErr> ⓘ
fn is_instance(&self, ty: &Bound<'py, PyAny>) -> Result<bool, PyErr> ⓘ
Checks whether this object is an instance of type ty
.
This is equivalent to the Python expression isinstance(self, ty)
.
fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool
fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool
Checks whether this object is an instance of exactly type ty
(not a subclass).
This is equivalent to the Python expression type(self) is ty
.
fn is_instance_of<T>(&self) -> boolwhere
T: PyTypeInfo,
fn is_instance_of<T>(&self) -> boolwhere
T: PyTypeInfo,
Checks whether this object is an instance of type T
.
This is equivalent to the Python expression isinstance(self, T)
,
if the type T
is known at compile time.
fn is_exact_instance_of<T>(&self) -> boolwhere
T: PyTypeInfo,
fn is_exact_instance_of<T>(&self) -> boolwhere
T: PyTypeInfo,
Checks whether this object is an instance of exactly type T
.
This is equivalent to the Python expression type(self) is T
,
if the type T
is known at compile time.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.