pub trait PyAnyMethods<'py>: Sealed {
Show 67 methods
// Required methods
fn is<T: AsPyPointer>(&self, other: &T) -> bool;
fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
where N: IntoPy<Py<PyString>>;
fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
where N: IntoPy<Py<PyString>>;
fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
where N: IntoPy<Py<PyString>>,
V: ToPyObject;
fn delattr<N>(&self, attr_name: N) -> PyResult<()>
where N: IntoPy<Py<PyString>>;
fn compare<O>(&self, other: O) -> PyResult<Ordering>
where O: ToPyObject;
fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp,
) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn neg(&self) -> PyResult<Bound<'py, PyAny>>;
fn pos(&self) -> PyResult<Bound<'py, PyAny>>;
fn abs(&self) -> PyResult<Bound<'py, PyAny>>;
fn bitnot(&self) -> PyResult<Bound<'py, PyAny>>;
fn lt<O>(&self, other: O) -> PyResult<bool>
where O: ToPyObject;
fn le<O>(&self, other: O) -> PyResult<bool>
where O: ToPyObject;
fn eq<O>(&self, other: O) -> PyResult<bool>
where O: ToPyObject;
fn ne<O>(&self, other: O) -> PyResult<bool>
where O: ToPyObject;
fn gt<O>(&self, other: O) -> PyResult<bool>
where O: ToPyObject;
fn ge<O>(&self, other: O) -> PyResult<bool>
where O: ToPyObject;
fn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>
where O1: ToPyObject,
O2: ToPyObject;
fn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>
where O: ToPyObject;
fn is_callable(&self) -> bool;
fn call(
&self,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, PyAny>>;
fn call0(&self) -> PyResult<Bound<'py, PyAny>>;
fn call1(
&self,
args: impl IntoPy<Py<PyTuple>>,
) -> PyResult<Bound<'py, PyAny>>;
fn call_method<N, A>(
&self,
name: N,
args: A,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, PyAny>>
where N: IntoPy<Py<PyString>>,
A: IntoPy<Py<PyTuple>>;
fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
where N: IntoPy<Py<PyString>>;
fn call_method1<N, A>(
&self,
name: N,
args: A,
) -> PyResult<Bound<'py, PyAny>>
where N: IntoPy<Py<PyString>>,
A: IntoPy<Py<PyTuple>>;
fn is_truthy(&self) -> PyResult<bool>;
fn is_none(&self) -> bool;
fn is_ellipsis(&self) -> bool;
fn is_empty(&self) -> PyResult<bool>;
fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>
where K: ToPyObject;
fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>
where K: ToPyObject,
V: ToPyObject;
fn del_item<K>(&self, key: K) -> PyResult<()>
where K: ToPyObject;
fn iter(&self) -> PyResult<Bound<'py, PyIterator>>;
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) -> PyResult<T>
where T: FromPyObjectBound<'a, 'py>;
fn get_refcnt(&self) -> isize;
fn repr(&self) -> PyResult<Bound<'py, PyString>>;
fn str(&self) -> PyResult<Bound<'py, PyString>>;
fn hash(&self) -> PyResult<isize>;
fn len(&self) -> PyResult<usize>;
fn dir(&self) -> PyResult<Bound<'py, PyList>>;
fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>;
fn is_exact_instance(&self, ty: &Bound<'py, PyAny>) -> bool;
fn is_instance_of<T: PyTypeInfo>(&self) -> bool;
fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool;
fn contains<V>(&self, value: V) -> PyResult<bool>
where V: ToPyObject;
fn py_super(&self) -> PyResult<Bound<'py, PySuper>>;
}
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§
Sourcefn is<T: AsPyPointer>(&self, other: &T) -> bool
fn is<T: AsPyPointer>(&self, other: &T) -> bool
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
.
Sourcefn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
fn hasattr<N>(&self, attr_name: N) -> PyResult<bool>
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"))
}
Sourcefn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
fn getattr<N>(&self, attr_name: N) -> PyResult<Bound<'py, PyAny>>
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"))
}
Sourcefn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
fn setattr<N, V>(&self, attr_name: N, value: V) -> PyResult<()>
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)
}
Sourcefn delattr<N>(&self, attr_name: N) -> PyResult<()>
fn delattr<N>(&self, attr_name: N) -> PyResult<()>
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
.
Sourcefn compare<O>(&self, other: O) -> PyResult<Ordering>where
O: ToPyObject,
fn compare<O>(&self, other: O) -> PyResult<Ordering>where
O: ToPyObject,
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_bound(py, 0_f64);
let b = PyFloat::new_bound(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_bound(py, 0_f64);
let b = PyString::new_bound(py, "zero");
assert!(a.compare(b).is_err());
Ok(())
})?;
Sourcefn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp,
) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp,
) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
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::*;
use pyo3::types::PyInt;
Python::with_gil(|py| -> PyResult<()> {
let a: Bound<'_, PyInt> = 0_u8.into_py(py).into_bound(py).downcast_into()?;
let b: Bound<'_, PyInt> = 42_u8.into_py(py).into_bound(py).downcast_into()?;
assert!(a.rich_compare(b, CompareOp::Le)?.is_truthy()?);
Ok(())
})?;
Sourcefn neg(&self) -> PyResult<Bound<'py, PyAny>>
fn neg(&self) -> PyResult<Bound<'py, PyAny>>
Computes the negative of self.
Equivalent to the Python expression -self
.
Sourcefn pos(&self) -> PyResult<Bound<'py, PyAny>>
fn pos(&self) -> PyResult<Bound<'py, PyAny>>
Computes the positive of self.
Equivalent to the Python expression +self
.
Sourcefn abs(&self) -> PyResult<Bound<'py, PyAny>>
fn abs(&self) -> PyResult<Bound<'py, PyAny>>
Computes the absolute of self.
Equivalent to the Python expression abs(self)
.
Sourcefn lt<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
fn lt<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
Tests whether this object is less than another.
This is equivalent to the Python expression self < other
.
Sourcefn le<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
fn le<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
Tests whether this object is less than or equal to another.
This is equivalent to the Python expression self <= other
.
Sourcefn eq<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
fn eq<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
Tests whether this object is equal to another.
This is equivalent to the Python expression self == other
.
Sourcefn ne<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
fn ne<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
Tests whether this object is not equal to another.
This is equivalent to the Python expression self != other
.
Sourcefn gt<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
fn gt<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
Tests whether this object is greater than another.
This is equivalent to the Python expression self > other
.
Sourcefn ge<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
fn ge<O>(&self, other: O) -> PyResult<bool>where
O: ToPyObject,
Tests whether this object is greater than or equal to another.
This is equivalent to the Python expression self >= other
.
Sourcefn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn add<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self + other
.
Sourcefn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn sub<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self - other
.
Sourcefn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn mul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self * other
.
Sourcefn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn matmul<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self @ other
.
Sourcefn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self / other
.
Sourcefn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn floor_div<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self // other
.
Sourcefn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn rem<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self % other
.
Sourcefn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn divmod<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes divmod(self, other)
.
Sourcefn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn lshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self << other
.
Sourcefn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn rshift<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self >> other
.
Sourcefn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>where
O1: ToPyObject,
O2: ToPyObject,
fn pow<O1, O2>(&self, other: O1, modulus: O2) -> PyResult<Bound<'py, PyAny>>where
O1: ToPyObject,
O2: ToPyObject,
Computes self ** other % modulus
(pow(self, other, modulus)
).
py.None()
may be passed for the modulus
.
Sourcefn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn bitand<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self & other
.
Sourcefn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn bitor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self | other
.
Sourcefn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
fn bitxor<O>(&self, other: O) -> PyResult<Bound<'py, PyAny>>where
O: ToPyObject,
Computes self ^ other
.
Sourcefn 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_bound(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.
Sourcefn call(
&self,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, PyAny>>
fn call( &self, args: impl IntoPy<Py<PyTuple>>, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<Bound<'py, PyAny>>
Calls the object.
This is equivalent to the Python expression self(*args, **kwargs)
.
§Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;
const CODE: &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_bound(py, CODE, "", "")?;
let fun = module.getattr("function")?;
let args = ("hello",);
let kwargs = PyDict::new_bound(py);
kwargs.set_item("cruel", "world")?;
let result = fun.call(args, Some(&kwargs))?;
assert_eq!(result.extract::<String>()?, "called with args and kwargs");
Ok(())
})
Sourcefn call0(&self) -> PyResult<Bound<'py, PyAny>>
fn call0(&self) -> PyResult<Bound<'py, PyAny>>
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_bound(py, "builtins")?;
let help = module.getattr("help")?;
help.call0()?;
Ok(())
})?;
This is equivalent to the Python expression help()
.
Sourcefn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<Bound<'py, PyAny>>
fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<Bound<'py, PyAny>>
Calls the object with only positional arguments.
This is equivalent to the Python expression self(*args)
.
§Examples
use pyo3::prelude::*;
const CODE: &str = r#"
def function(*args, **kwargs):
assert args == ("hello",)
assert kwargs == {}
return "called with args"
"#;
Python::with_gil(|py| {
let module = PyModule::from_code_bound(py, CODE, "", "")?;
let fun = module.getattr("function")?;
let args = ("hello",);
let result = fun.call1(args)?;
assert_eq!(result.extract::<String>()?, "called with args");
Ok(())
})
Sourcefn call_method<N, A>(
&self,
name: N,
args: A,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, PyAny>>
fn call_method<N, A>( &self, name: N, args: A, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<Bound<'py, PyAny>>
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;
const CODE: &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_bound(py, CODE, "", "")?;
let instance = module.getattr("a")?;
let args = ("hello",);
let kwargs = PyDict::new_bound(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(())
})
Sourcefn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
fn call_method0<N>(&self, name: N) -> PyResult<Bound<'py, PyAny>>
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::*;
const CODE: &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_bound(py, CODE, "", "")?;
let instance = module.getattr("a")?;
let result = instance.call_method0("method")?;
assert_eq!(result.extract::<String>()?, "called with no arguments");
Ok(())
})
Sourcefn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>>
fn call_method1<N, A>(&self, name: N, args: A) -> PyResult<Bound<'py, PyAny>>
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::*;
const CODE: &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_bound(py, CODE, "", "")?;
let instance = module.getattr("a")?;
let args = ("hello",);
let result = instance.call_method1("method", args)?;
assert_eq!(result.extract::<String>()?, "called with args");
Ok(())
})
Sourcefn is_truthy(&self) -> PyResult<bool>
fn is_truthy(&self) -> PyResult<bool>
Returns whether the object is considered to be true.
This is equivalent to the Python expression bool(self)
.
Sourcefn 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
.
Sourcefn is_ellipsis(&self) -> bool
fn is_ellipsis(&self) -> bool
Returns whether the object is Ellipsis, e.g. ...
.
This is equivalent to the Python expression self is ...
.
Sourcefn is_empty(&self) -> PyResult<bool>
fn is_empty(&self) -> PyResult<bool>
Returns true if the sequence or mapping has a length of 0.
This is equivalent to the Python expression len(self) == 0
.
Sourcefn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>where
K: ToPyObject,
fn get_item<K>(&self, key: K) -> PyResult<Bound<'py, PyAny>>where
K: ToPyObject,
Gets an item from the collection.
This is equivalent to the Python expression self[key]
.
Sourcefn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>where
K: ToPyObject,
V: ToPyObject,
fn set_item<K, V>(&self, key: K, value: V) -> PyResult<()>where
K: ToPyObject,
V: ToPyObject,
Sets a collection item value.
This is equivalent to the Python expression self[key] = value
.
Sourcefn del_item<K>(&self, key: K) -> PyResult<()>where
K: ToPyObject,
fn del_item<K>(&self, key: K) -> PyResult<()>where
K: ToPyObject,
Deletes an item from the collection.
This is equivalent to the Python expression del self[key]
.
Sourcefn iter(&self) -> PyResult<Bound<'py, PyIterator>>
fn iter(&self) -> PyResult<Bound<'py, PyIterator>>
Takes an object and returns an iterator for it.
This is typically a new iterator but if the argument is an iterator, this returns itself.
Sourcefn get_type(&self) -> Bound<'py, PyType>
fn get_type(&self) -> Bound<'py, PyType>
Returns the Python type object for this object’s type.
Sourcefn get_type_ptr(&self) -> *mut PyTypeObject
fn get_type_ptr(&self) -> *mut PyTypeObject
Returns the Python type pointer for this object.
Sourcefn 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_bound(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(())
})
Sourcefn 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_bound(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());
})
Sourcefn 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, PyLong};
Python::with_gil(|py| {
let b = PyBool::new_bound(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::<PyLong>().is_ok());
assert!(any.downcast_exact::<PyLong>().is_err());
assert!(any.downcast_exact::<PyBool>().is_ok());
});
Sourcefn 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
.
Sourceunsafe 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.
Sourceunsafe 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.
Sourcefn extract<'a, T>(&'a self) -> PyResult<T>where
T: FromPyObjectBound<'a, 'py>,
fn extract<'a, T>(&'a self) -> PyResult<T>where
T: FromPyObjectBound<'a, 'py>,
Extracts some type from the Python object.
This is a wrapper function around
FromPyObject::extract_bound()
.
Sourcefn get_refcnt(&self) -> isize
fn get_refcnt(&self) -> isize
Returns the reference count for the Python object.
Sourcefn repr(&self) -> PyResult<Bound<'py, PyString>>
fn repr(&self) -> PyResult<Bound<'py, PyString>>
Computes the “repr” representation of self.
This is equivalent to the Python expression repr(self)
.
Sourcefn str(&self) -> PyResult<Bound<'py, PyString>>
fn str(&self) -> PyResult<Bound<'py, PyString>>
Computes the “str” representation of self.
This is equivalent to the Python expression str(self)
.
Sourcefn hash(&self) -> PyResult<isize>
fn hash(&self) -> PyResult<isize>
Retrieves the hash code of self.
This is equivalent to the Python expression hash(self)
.
Sourcefn len(&self) -> PyResult<usize>
fn len(&self) -> PyResult<usize>
Returns the length of the sequence or mapping.
This is equivalent to the Python expression len(self)
.
Sourcefn dir(&self) -> PyResult<Bound<'py, PyList>>
fn dir(&self) -> PyResult<Bound<'py, PyList>>
Returns the list of attributes of this object.
This is equivalent to the Python expression dir(self)
.
Sourcefn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>
fn is_instance(&self, ty: &Bound<'py, PyAny>) -> PyResult<bool>
Checks whether this object is an instance of type ty
.
This is equivalent to the Python expression isinstance(self, ty)
.
Sourcefn 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
.
Sourcefn is_instance_of<T: PyTypeInfo>(&self) -> bool
fn is_instance_of<T: PyTypeInfo>(&self) -> bool
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.
Sourcefn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool
fn is_exact_instance_of<T: PyTypeInfo>(&self) -> bool
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.
Sourcefn contains<V>(&self, value: V) -> PyResult<bool>where
V: ToPyObject,
fn contains<V>(&self, value: V) -> PyResult<bool>where
V: ToPyObject,
Determines if self contains value
.
This is equivalent to the Python expression value in self
.
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.