Struct cpython::PyObject

source ·
#[repr(C)]
pub struct PyObject { /* private fields */ }
Expand description

Represents a reference to a Python object.

Python objects are reference counted. Calling clone_ref() on a PyObject will return a new reference to the same object (thus incrementing the reference count). The Drop implementation will automatically decrement the reference count. You can also call release_ref() to explicitly decrement the reference count. This is slightly faster than relying on automatic drop, because release_ref does not need to check whether the GIL needs to be acquired.

PyObject can be used with all Python objects, since all python types derive from object. This crate also contains other, more specific types that serve as references to Python objects (e.g. PyTuple for Python tuples, etc.).

You can convert from any Python object to PyObject by calling as_object() or into_object() from the PythonObject trait. In the other direction, you can call cast_as() or cast_into() on PyObject to convert to more specific object types.

Most of the interesting methods are provided by the ObjectProtocol trait.

Implementations§

source§

impl PyObject

source

pub unsafe fn from_owned_ptr(_py: Python<'_>, ptr: *mut PyObject) -> PyObject

Creates a PyObject instance for the given FFI pointer. This moves ownership over the pointer into the PyObject. Undefined behavior if the pointer is NULL or invalid.

source

pub unsafe fn from_borrowed_ptr(_py: Python<'_>, ptr: *mut PyObject) -> PyObject

Creates a PyObject instance for the given FFI pointer. Calls Py_INCREF() on the ptr. Undefined behavior if the pointer is NULL or invalid.

source

pub unsafe fn from_owned_ptr_opt( py: Python<'_>, ptr: *mut PyObject ) -> Option<PyObject>

Creates a PyObject instance for the given FFI pointer. This moves ownership over the pointer into the PyObject. Returns None for null pointers; undefined behavior if the pointer is invalid.

source

pub unsafe fn from_borrowed_ptr_opt( py: Python<'_>, ptr: *mut PyObject ) -> Option<PyObject>

Returns None for null pointers; undefined behavior if the pointer is invalid.

source

pub fn as_ptr(&self) -> *mut PyObject

Gets the underlying FFI pointer. Returns a borrowed pointer.

source

pub fn steal_ptr(self) -> *mut PyObject

Gets the underlying FFI pointer. Consumes self without calling Py_DECREF(), thus returning an owned pointer.

source

pub unsafe fn borrow_from_ptr(ptr: &*mut PyObject) -> &PyObject

Transmutes an FFI pointer to &PyObject. Undefined behavior if the pointer is NULL or invalid.

source

pub unsafe fn borrow_from_owned_ptr_slice(ptr: &[*mut PyObject]) -> &[PyObject]

Transmutes a slice of owned FFI pointers to &[PyObject]. Undefined behavior if any pointer in the slice is NULL or invalid.

source

pub fn get_refcnt(&self, _py: Python<'_>) -> usize

Gets the reference count of this Python object.

source

pub fn get_type(&self, py: Python<'_>) -> PyType

Gets the Python type object for this object’s type.

source

pub unsafe fn unchecked_cast_into<T>(self) -> T
where T: PythonObject,

Casts the PyObject to a concrete Python object type. Causes undefined behavior if the object is not of the expected type. This is a wrapper function around PythonObject::unchecked_downcast_from().

source

pub fn cast_into<T>( self, py: Python<'_> ) -> Result<T, PythonObjectDowncastError<'_>>

Casts the PyObject to a concrete Python object type. Fails with PythonObjectDowncastError if the object is not of the expected type. This is a wrapper function around PythonObjectWithCheckedDowncast::downcast_from().

source

pub unsafe fn unchecked_cast_as<T>(&self) -> &T
where T: PythonObject,

Casts the PyObject to a concrete Python object type. Causes undefined behavior if the object is not of the expected type. This is a wrapper function around PythonObject::unchecked_downcast_borrow_from().

source

pub fn cast_as<'s, 'p, T>( &'s self, py: Python<'p> ) -> Result<&'s T, PythonObjectDowncastError<'p>>

Casts the PyObject to a concrete Python object type. Fails with PythonObjectDowncastError if the object is not of the expected type. This is a wrapper function around PythonObjectWithCheckedDowncast::downcast_borrow_from().

source

pub fn extract<'a, T>(&'a self, py: Python<'_>) -> PyResult<T>
where T: FromPyObject<'a>,

Extracts some type from the Python object. This is a wrapper function around FromPyObject::from_py_object().

source

pub fn is_none(&self, _py: Python<'_>) -> bool

True if this is None in Python.

Trait Implementations§

source§

impl BaseObject for PyObject

source§

fn size() -> usize

Gets the size of the object, in bytes.
§

type InitType = ()

source§

unsafe fn alloc( py: Python<'_>, ty: &PyType, _init_val: () ) -> PyResult<PyObject>

Allocates a new object (usually by calling ty->tp_alloc), and initializes it using init_val. ty must be derived from the Self type, and the resulting object must be of type ty.
source§

unsafe fn dealloc(_py: Python<'_>, obj: *mut PyObject)

Calls the rust destructor for the object and frees the memory (usually by calling ptr->ob_type->tp_free). This function is used as tp_dealloc implementation.
source§

impl Debug for PyObject

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Display for PyObject

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Drop for PyObject

Dropping a PyObject decrements the reference count on the object by 1.

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'s> FromPyObject<'s> for &'s PyObject

source§

fn extract(py: Python<'_>, obj: &'s PyObject) -> PyResult<&'s PyObject>

Extracts Self from the source PyObject.
source§

impl<'s> FromPyObject<'s> for PyObject

source§

fn extract(py: Python<'_>, obj: &'s PyObject) -> PyResult<PyObject>

Extracts Self from the source PyObject.
source§

impl NumberProtocol for PyObject

source§

fn add(&self, py: Python<'_>, other: impl ToPyObject) -> PyResult<PyObject>

Perform addition (self + other) Read more
source§

fn subtract(&self, py: Python<'_>, other: impl ToPyObject) -> PyResult<PyObject>

Perform subtraction (self - other) Read more
source§

fn multiply(&self, py: Python<'_>, other: impl ToPyObject) -> PyResult<PyObject>

Perform multiplication (self * other) Read more
source§

fn matrix_multiply( &self, py: Python<'_>, other: impl ToPyObject ) -> PyResult<PyObject>

Perform matrix multiplication, equivalent to the Python expression self @ other Read more
source§

fn power(&self, py: Python<'_>, other: impl ToPyObject) -> PyResult<PyObject>

Perform exponentiation, equivalent to the Python expression self ** other, or the two-argument form of the builtin method pow: pow(self, other) Read more
source§

fn power_modulo( &self, py: Python<'_>, exp: impl ToPyObject, z: impl ToPyObject ) -> PyResult<PyObject>

Perform exponentiation modulo an integer, mathematically equivalent to self ** other % mod but computed much more efficiently. Read more
source§

fn true_divide( &self, py: Python<'_>, other: impl ToPyObject ) -> PyResult<PyObject>

Perform the “true division” operation, equivalent to the Python expression self / other, Read more
source§

fn floor_divide( &self, py: Python<'_>, other: impl ToPyObject ) -> PyResult<PyObject>

Perform the “floor division” operation, equivalent to the Python expression self // other, Read more
source§

fn modulo(&self, py: Python<'_>, other: impl ToPyObject) -> PyResult<PyObject>

Return the remainder of dividing self by other, equivalent to the Python expression self % other Read more
source§

fn div_mod(&self, py: Python<'_>, other: impl ToPyObject) -> PyResult<PyObject>

Perform combined division and modulo, equivalent to the builtin method divmod(self, other) Read more
source§

fn negative(&self, py: Python<'_>) -> PyResult<PyObject>

Perform the negation of self (-self) Read more
source§

fn positive(&self, py: Python<'_>) -> PyResult<PyObject>

Invoke the ‘positive’ operation, equivalent to the Python expression +self Read more
source§

fn absolute(&self, py: Python<'_>) -> PyResult<PyObject>

Return the absolute value of self, equivalent to calling the builtin function abs Read more
source§

fn bitwise_invert(&self, py: Python<'_>) -> PyResult<PyObject>

Perform the bitwise negation of self, equivalent to the Python expression ~self Read more
source§

fn left_shift( &self, py: Python<'_>, bits: impl ToPyObject ) -> PyResult<PyObject>

Shift this value to the left by the specified number of bits, equivalent to the Python expression self << bits Read more
source§

fn right_shift( &self, py: Python<'_>, bits: impl ToPyObject ) -> PyResult<PyObject>

Shift this value to the right by the specified number of bits, equivalent to the Python expression self >> bits Read more
source§

fn bitwise_and( &self, py: Python<'_>, other: impl ToPyObject ) -> PyResult<PyObject>

Perform the “bitwise and” of self & other Read more
source§

fn bitwise_xor( &self, py: Python<'_>, other: impl ToPyObject ) -> PyResult<PyObject>

Perform the “bitwise exclusive or”, equivalent to Python expression self ^ other Read more
source§

fn bitwise_or( &self, py: Python<'_>, other: impl ToPyObject ) -> PyResult<PyObject>

Perform the “bitwise or” of self | other Read more
source§

fn to_int(&self, py: Python<'_>) -> PyResult<PyLong>

Convert this object to an integer, equivalent to the builtin function int(self) Read more
source§

fn to_float(&self, py: Python<'_>) -> PyResult<PyFloat>

Convert this object to a float, equivalent to the builtin function float(self) Read more
source§

fn to_index(&self, py: Python<'_>) -> PyResult<PyLong>

Losslessly convert this object to an integer index, as if calling operator.index() Read more
source§

impl ObjectProtocol for PyObject

source§

fn hasattr<N>(&self, py: Python<'_>, attr_name: N) -> PyResult<bool>
where N: ToPyObject,

Determines whether this object has the given attribute. This is equivalent to the Python expression ‘hasattr(self, attr_name)’.
source§

fn getattr<N>(&self, py: Python<'_>, attr_name: N) -> PyResult<PyObject>
where N: ToPyObject,

Retrieves an attribute value. This is equivalent to the Python expression ‘self.attr_name’.
source§

fn setattr<N, V>(&self, py: Python<'_>, attr_name: N, value: V) -> PyResult<()>
where N: ToPyObject, V: ToPyObject,

Sets an attribute value. This is equivalent to the Python expression ‘self.attr_name = value’.
source§

fn delattr<N>(&self, py: Python<'_>, attr_name: N) -> PyResult<()>
where N: ToPyObject,

Deletes an attribute. This is equivalent to the Python expression ‘del self.attr_name’.
source§

fn compare<O>(&self, py: Python<'_>, other: O) -> PyResult<Ordering>
where O: ToPyObject,

Compares two Python objects. Read more
source§

fn rich_compare<O>( &self, py: Python<'_>, other: O, compare_op: CompareOp ) -> PyResult<PyObject>
where O: ToPyObject,

Compares two Python objects. Read more
source§

fn repr(&self, py: Python<'_>) -> PyResult<PyString>

Compute the string representation of self. This is equivalent to the Python expression ‘repr(self)’.
source§

fn str(&self, py: Python<'_>) -> PyResult<PyString>

Compute the string representation of self. This is equivalent to the Python expression ‘str(self)’.
source§

fn is_callable(&self, _py: Python<'_>) -> bool

Determines whether this object is callable.
source§

fn call<A>( &self, py: Python<'_>, args: A, kwargs: Option<&PyDict> ) -> PyResult<PyObject>
where A: ToPyObject<ObjectType = PyTuple>,

Calls the object. This is equivalent to the Python expression: ‘self(*args, **kwargs)’ Read more
source§

fn call_method<A>( &self, py: Python<'_>, name: &str, args: A, kwargs: Option<&PyDict> ) -> PyResult<PyObject>
where A: ToPyObject<ObjectType = PyTuple>,

Calls a method on the object. This is equivalent to the Python expression: ‘self.name(*args, **kwargs)’ Read more
source§

fn hash(&self, py: Python<'_>) -> PyResult<Py_hash_t>

Retrieves the hash code of the object. This is equivalent to the Python expression: ‘hash(self)’
source§

fn is_true(&self, py: Python<'_>) -> PyResult<bool>

Returns whether the object is considered to be true. This is equivalent to the Python expression: ‘not not self’
source§

fn len(&self, py: Python<'_>) -> PyResult<usize>

Returns the length of the sequence or mapping. This is equivalent to the Python expression: ‘len(self)’
source§

fn get_item<K>(&self, py: Python<'_>, key: K) -> PyResult<PyObject>
where K: ToPyObject,

This is equivalent to the Python expression: ‘self[key]’
source§

fn set_item<K, V>(&self, py: Python<'_>, key: K, value: V) -> PyResult<()>
where K: ToPyObject, V: ToPyObject,

Sets an item value. This is equivalent to the Python expression ‘self[key] = value’.
source§

fn del_item<K>(&self, py: Python<'_>, key: K) -> PyResult<()>
where K: ToPyObject,

Deletes an item. This is equivalent to the Python expression ‘del self[key]’.
source§

fn iter<'p>(&self, py: Python<'p>) -> PyResult<PyIterator<'p>>

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.
source§

impl PartialEq for PyObject

PyObject implements the == operator using reference equality: obj1 == obj2 in rust is equivalent to obj1 is obj2 in Python.

source§

fn eq(&self, o: &PyObject) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PythonObject for PyObject

source§

fn as_object(&self) -> &PyObject

Casts the Python object to PyObject.
source§

fn into_object(self) -> PyObject

Casts the Python object to PyObject.
source§

unsafe fn unchecked_downcast_from(o: PyObject) -> PyObject

Unchecked downcast from PyObject to Self. Undefined behavior if the input object does not have the expected type.
source§

unsafe fn unchecked_downcast_borrow_from(o: &PyObject) -> &PyObject

Unchecked downcast from PyObject to Self. Undefined behavior if the input object does not have the expected type.
source§

impl PythonObjectWithCheckedDowncast for PyObject

source§

fn downcast_from( _py: Python<'_>, obj: PyObject ) -> Result<PyObject, PythonObjectDowncastError<'_>>

Cast from PyObject to a concrete Python object type.
source§

fn downcast_borrow_from<'a, 'p>( _py: Python<'p>, obj: &'a PyObject ) -> Result<&'a PyObject, PythonObjectDowncastError<'p>>

Cast from PyObject to a concrete Python object type.
source§

impl PythonObjectWithTypeObject for PyObject

source§

fn type_object(py: Python<'_>) -> PyType

Retrieves the type object for this Python object type.
source§

impl ToPyObject for PyObject

Identity conversion: allows using existing PyObject instances where T: ToPyObject is expected.

§

type ObjectType = PyObject

source§

fn to_py_object(&self, py: Python<'_>) -> PyObject

Converts self into a Python object.
source§

fn into_py_object(self, _py: Python<'_>) -> PyObject

Converts self into a Python object. Read more
source§

fn with_borrowed_ptr<F, R>(&self, _py: Python<'_>, f: F) -> R
where F: FnOnce(*mut PyObject) -> R,

Converts self into a Python object and calls the specified closure on the native FFI pointer underlying the Python object. Read more
source§

impl Eq for PyObject

PyObject implements the == operator using reference equality: obj1 == obj2 in rust is equivalent to obj1 is obj2 in Python.

source§

impl Send for PyObject

source§

impl Sync for PyObject

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> PyClone for T
where T: PythonObject,

source§

fn clone_ref(&self, py: Python<'_>) -> T

source§

impl<T> PyDrop for T
where T: PythonObject,

source§

fn release_ref(self, _py: Python<'_>)

source§

impl<T> RefFromPyObject for T
where &'a T: for<'a> FromPyObject<'a>, T: ?Sized,

source§

fn with_extracted<F, R>( py: Python<'_>, obj: &PyObject, f: F ) -> Result<R, PyErr>
where F: FnOnce(&T) -> R,

source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.