⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here

Type Alias Dict

Source
type Dict<'py> = Bound<'py, PyDict>;

Aliased Type§

struct Dict<'py>(/* private fields */);

Implementations

§

impl<'py, T> Bound<'py, T>

pub fn py(&self) -> Python<'py>

Returns the GIL token associated with this object.

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

Returns the raw FFI pointer represented by self.

§Safety

Callers are responsible for ensuring that the pointer does not outlive self.

The reference is borrowed; callers should not decrease the reference count when they are finished with the pointer.

pub fn into_ptr(self) -> *mut PyObject

Returns an owned raw FFI pointer represented by self.

§Safety

The reference is owned; when finished the caller should either transfer ownership of the pointer or decrease the reference count (e.g. with pyo3::ffi::Py_DecRef).

pub fn as_any(&self) -> &Bound<'py, PyAny>

Helper to cast to Bound<'py, PyAny>.

pub fn into_any(self) -> Bound<'py, PyAny>

Helper to cast to Bound<'py, PyAny>, transferring ownership.

pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T>

Casts this Bound<T> to a Borrowed<T> smart pointer.

pub fn unbind(self) -> Py<T>

Removes the connection for this Bound<T> from the GIL, allowing it to cross thread boundaries.

pub fn as_unbound(&self) -> &Py<T>

Removes the connection for this Bound<T> from the GIL, allowing it to cross thread boundaries, without transferring ownership.

§

impl<'py, T> Bound<'py, T>
where T: PyClass,

pub fn borrow(&self) -> PyRef<'py, T>

Immutably borrows the value T.

This borrow lasts while the returned [PyRef] exists. Multiple immutable borrows can be taken out at the same time.

For frozen classes, the simpler [get][Self::get] is available.

§Examples
#[pyclass]
struct Foo {
    inner: u8,
}

Python::with_gil(|py| -> PyResult<()> {
    let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
    let inner: &u8 = &foo.borrow().inner;

    assert_eq!(*inner, 73);
    Ok(())
})?;
§Panics

Panics if the value is currently mutably borrowed. For a non-panicking variant, use try_borrow.

pub fn borrow_mut(&self) -> PyRefMut<'py, T>
where T: PyClass<Frozen = False>,

Mutably borrows the value T.

This borrow lasts while the returned [PyRefMut] exists.

§Examples
#[pyclass]
struct Foo {
    inner: u8,
}

Python::with_gil(|py| -> PyResult<()> {
    let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
    foo.borrow_mut().inner = 35;

    assert_eq!(foo.borrow().inner, 35);
    Ok(())
})?;
§Panics

Panics if the value is currently borrowed. For a non-panicking variant, use try_borrow_mut.

pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError>

Attempts to immutably borrow the value T, returning an error if the value is currently mutably borrowed.

The borrow lasts while the returned [PyRef] exists.

This is the non-panicking variant of borrow.

For frozen classes, the simpler [get][Self::get] is available.

pub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
where T: PyClass<Frozen = False>,

Attempts to mutably borrow the value T, returning an error if the value is currently borrowed.

The borrow lasts while the returned [PyRefMut] exists.

This is the non-panicking variant of borrow_mut.

pub fn get(&self) -> &T
where T: PyClass<Frozen = True> + Sync,

Provide an immutable borrow of the value T without acquiring the GIL.

This is available if the class is [frozen][macro@crate::pyclass] and Sync.

§Examples
use std::sync::atomic::{AtomicUsize, Ordering};

#[pyclass(frozen)]
struct FrozenCounter {
    value: AtomicUsize,
}

Python::with_gil(|py| {
    let counter = FrozenCounter { value: AtomicUsize::new(0) };

    let py_counter = Bound::new(py, counter).unwrap();

    py_counter.get().value.fetch_add(1, Ordering::Relaxed);
});

pub fn as_super(&self) -> &Bound<'py, <T as PyClassImpl>::BaseType>

Upcast this Bound<PyClass> to its base type by reference.

If this type defined an explicit base class in its pyclass declaration (e.g. #[pyclass(extends = BaseType)]), the returned type will be &Bound<BaseType>. If an explicit base class was not declared, the return value will be &Bound<PyAny> (making this method equivalent to as_any).

This method is particularly useful for calling methods defined in an extension trait that has been implemented for Bound<BaseType>.

See also the into_super method to upcast by value, and the [PyRef::as_super]/[PyRefMut::as_super] methods for upcasting a pyclass that has already been borrowed.

§Example: Calling a method defined on the Bound base type
use pyo3::prelude::*;

#[pyclass(subclass)]
struct BaseClass;

trait MyClassMethods<'py> {
    fn pyrepr(&self) -> PyResult<String>;
}
impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> {
    fn pyrepr(&self) -> PyResult<String> {
        self.call_method0("__repr__")?.extract()
    }
}

#[pyclass(extends = BaseClass)]
struct SubClass;

Python::with_gil(|py| {
    let obj = Bound::new(py, (SubClass, BaseClass)).unwrap();
    assert!(obj.as_super().pyrepr().is_ok());
})

pub fn into_super(self) -> Bound<'py, <T as PyClassImpl>::BaseType>

Upcast this Bound<PyClass> to its base type by value.

If this type defined an explicit base class in its pyclass declaration (e.g. #[pyclass(extends = BaseType)]), the returned type will be Bound<BaseType>. If an explicit base class was not declared, the return value will be Bound<PyAny> (making this method equivalent to into_any).

This method is particularly useful for calling methods defined in an extension trait that has been implemented for Bound<BaseType>.

See also the as_super method to upcast by reference, and the [PyRef::into_super]/[PyRefMut::into_super] methods for upcasting a pyclass that has already been borrowed.

§Example: Calling a method defined on the Bound base type
use pyo3::prelude::*;

#[pyclass(subclass)]
struct BaseClass;

trait MyClassMethods<'py> {
    fn pyrepr(self) -> PyResult<String>;
}
impl<'py> MyClassMethods<'py> for Bound<'py, BaseClass> {
    fn pyrepr(self) -> PyResult<String> {
        self.call_method0("__repr__")?.extract()
    }
}

#[pyclass(extends = BaseClass)]
struct SubClass;

Python::with_gil(|py| {
    let obj = Bound::new(py, (SubClass, BaseClass)).unwrap();
    assert!(obj.into_super().pyrepr().is_ok());
})
§

impl<'py, T> Bound<'py, T>
where T: PyClass,

pub fn new( py: Python<'py>, value: impl Into<PyClassInitializer<T>>, ) -> Result<Bound<'py, T>, PyErr>

Creates a new instance Bound<T> of a #[pyclass] on the Python heap.

§Examples
use pyo3::prelude::*;

#[pyclass]
struct Foo {/* fields omitted */}

let foo: Py<Foo> = Python::with_gil(|py| -> PyResult<_> {
    let foo: Bound<'_, Foo> = Bound::new(py, Foo {})?;
    Ok(foo.into())
})?;

Trait Implementations

§

impl<T> AsPyPointer for Bound<'_, T>

§

fn as_ptr(&self) -> *mut PyObject

Returns the underlying FFI pointer as a borrowed pointer.
§

impl<'py, T> AsRef<Bound<'py, PyAny>> for Bound<'py, T>

§

fn as_ref(&self) -> &Bound<'py, PyAny>

Converts this type into a shared reference of the (usually inferred) input type.
§

impl<'py, T> BoundObject<'py, T> for Bound<'py, T>

§

type Any = Bound<'py, PyAny>

Type erased version of Self
§

fn as_borrowed(&self) -> Borrowed<'_, 'py, T>

Borrow this smart pointer.
§

fn into_bound(self) -> Bound<'py, T>

Turns this smart pointer into an owned [Bound<'py, T>]
§

fn into_any(self) -> <Bound<'py, T> as BoundObject<'py, T>>::Any

Upcast the target type of this smart pointer
§

fn into_ptr(self) -> *mut PyObject

Turn this smart pointer into a strong reference pointer
§

fn as_ptr(&self) -> *mut PyObject

Turn this smart pointer into a borrowed reference pointer
§

fn unbind(self) -> Py<T>

Turn this smart pointer into an owned [Py<T>]
§

impl<T> Clone for Bound<'_, T>

§

fn clone(&self) -> Bound<'_, T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T> Debug for Bound<'_, T>

§

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

Formats the value using the given formatter. Read more
§

impl<'py, T> Deref for Bound<'py, T>
where T: DerefToPyAny,

§

type Target = Bound<'py, PyAny>

The resulting type after dereferencing.
§

fn deref(&self) -> &Bound<'py, PyAny>

Dereferences the value.
§

impl<T> Display for Bound<'_, T>

§

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

Formats the value using the given formatter. Read more
§

impl<T> Drop for Bound<'_, T>

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl<'a, 'py, T> From<BoundRef<'a, 'py, T>> for Bound<'py, T>

§

fn from(bound: BoundRef<'a, 'py, T>) -> Bound<'py, T>

Converts to this type from the input type.
§

impl<'py, T> FromPyObject<'py> for Bound<'py, T>
where T: PyTypeCheck,

§

fn extract_bound(ob: &Bound<'py, PyAny>) -> Result<Bound<'py, T>, PyErr>

Extracts Self from the source PyObject.

§

fn type_input() -> TypeInfo

Extracts the type hint information for this type when it appears as an argument. Read more
§

impl<'py> IntoIterator for Bound<'py, PyDict>

§

type Item = (Bound<'py, PyAny>, Bound<'py, PyAny>)

The type of the elements being iterated over.
§

type IntoIter = BoundDictIterator<'py>

Which kind of iterator are we turning this into?
§

fn into_iter(self) -> <Bound<'py, PyDict> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
§

impl<T> IntoPy<Py<PyAny>> for Bound<'_, T>

§

fn into_py(self, _py: Python<'_>) -> Py<PyAny>

👎Deprecated since 0.23.0: IntoPy is going to be replaced by IntoPyObject. See the migration guide (https://pyo3.rs/v0.23.0/migration) for more information.

Converts a Bound instance to PyObject.

§

impl<'py, T> IntoPyObject<'py> for Bound<'py, T>

§

type Target = T

The Python output type
§

type Output = Bound<'py, <Bound<'py, T> as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
§

type Error = Infallible

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

fn into_pyobject( self, _py: Python<'py>, ) -> Result<<Bound<'py, T> as IntoPyObject<'py>>::Output, <Bound<'py, T> as IntoPyObject<'py>>::Error>

Performs the conversion.
§

fn type_output() -> TypeInfo

Extracts the type hint information for this type when it appears as a return value. Read more
§

#[doc(hidden)] fn owned_sequence_into_pyobject<I>( iter: I, py: Python<'py>, _: Token, ) -> Result<Bound<'py, PyAny>, PyErr>
where I: IntoIterator<Item = Self> + AsRef<[Self]>, <I as IntoIterator>::IntoIter: ExactSizeIterator<Item = Self>,

Converts sequence of Self into a Python object. Used to specialize Vec<u8>, [u8; N] and SmallVec<[u8; N]> as a sequence of bytes into a bytes object.
§

#[doc(hidden)] fn borrowed_sequence_into_pyobject<I>( iter: I, py: Python<'py>, _: Token, ) -> Result<Bound<'py, PyAny>, PyErr>
where Self: Reference, I: IntoIterator<Item = Self> + AsRef<[Self::BaseType]>, <I as IntoIterator>::IntoIter: ExactSizeIterator<Item = Self>,

Converts sequence of Self into a Python object. Used to specialize &[u8] and Cow<[u8]> as a sequence of bytes into a bytes object.
§

impl<'py> PyDictMethods<'py> for Bound<'py, PyDict>

§

fn copy(&self) -> Result<Bound<'py, PyDict>, PyErr>

Returns a new dictionary that contains the same key-value pairs as self. Read more
§

fn clear(&self)

Empties an existing dictionary of all key-value pairs.
§

fn len(&self) -> usize

Return the number of items in the dictionary. Read more
§

fn is_empty(&self) -> bool

Checks if the dict is empty, i.e. len(self) == 0.
§

fn contains<K>(&self, key: K) -> Result<bool, PyErr>
where K: IntoPyObject<'py>,

Determines if the dictionary contains the specified key. Read more
§

fn get_item<K>(&self, key: K) -> Result<Option<Bound<'py, PyAny>>, PyErr>
where K: IntoPyObject<'py>,

Gets an item from the dictionary. Read more
§

fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr>
where K: IntoPyObject<'py>, V: IntoPyObject<'py>,

Sets an item value. Read more
§

fn del_item<K>(&self, key: K) -> Result<(), PyErr>
where K: IntoPyObject<'py>,

Deletes an item. Read more
§

fn keys(&self) -> Bound<'py, PyList>

Returns a list of dict keys. Read more
§

fn values(&self) -> Bound<'py, PyList>

Returns a list of dict values. Read more
§

fn items(&self) -> Bound<'py, PyList>

Returns a list of dict items. Read more
§

fn iter(&self) -> BoundDictIterator<'py>

Returns an iterator of (key, value) pairs in this dictionary. Read more
§

fn locked_for_each<F>(&self, f: F) -> Result<(), PyErr>
where F: Fn(Bound<'py, PyAny>, Bound<'py, PyAny>) -> Result<(), PyErr>,

Iterates over the contents of this dictionary while holding a critical section on the dict. This is useful when the GIL is disabled and the dictionary is shared between threads. It is not guaranteed that the dictionary will not be modified during iteration when the closure calls arbitrary Python code that releases the critical section held by the iterator. Otherwise, the dictionary will not be modified during iteration. Read more
§

fn as_mapping(&self) -> &Bound<'py, PyMapping>

Returns self cast as a PyMapping.
§

fn into_mapping(self) -> Bound<'py, PyMapping>

Returns self cast as a PyMapping.
§

fn update(&self, other: &Bound<'_, PyMapping>) -> Result<(), PyErr>

Update this dictionary with the key/value pairs from another. Read more
§

fn update_if_missing(&self, other: &Bound<'_, PyMapping>) -> Result<(), PyErr>

Add key/value pairs from another dictionary to this one only when they do not exist in this. Read more
§

impl<T> ToPyObject for Bound<'_, T>

§

fn to_object(&self, py: Python<'_>) -> Py<PyAny>

👎Deprecated since 0.23.0: ToPyObject is going to be replaced by IntoPyObject. See the migration guide (https://pyo3.rs/v0.23.0/migration) for more information.

Converts &Bound instance -> PyObject, increasing the reference count.