pub trait IntoPyObject<'py>: Sized {
type Target;
type Output: BoundObject<'py, Self::Target>;
type Error: Into<PyErr>;
// Required method
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>;
// Provided method
fn type_output() -> TypeInfo { ... }
}
Expand description
Defines a conversion from a Rust type to a Python object, which may fail.
This trait has #[derive(IntoPyObject)]
to automatically implement it for simple types and
#[derive(IntoPyObjectRef)]
to implement the same for references.
It functions similarly to std’s TryInto
trait, but requires a GIL token
as an argument.
The into_pyobject
method is designed for maximum flexibility and efficiency; it
- allows for a concrete Python type to be returned (the
Target
associated type) - allows for the smart pointer containing the Python object to be either
Bound<'py, Self::Target>
orBorrowed<'a, 'py, Self::Target>
to avoid unnecessary reference counting overhead - allows for a custom error type to be returned in the event of a conversion error to avoid unnecessarily creating a Python exception
§See also
- The
IntoPyObjectExt
trait, which provides convenience methods for common usages ofIntoPyObject
which erase type information and convert errors toPyErr
.
Required Associated Types§
Sourcetype Output: BoundObject<'py, Self::Target>
type Output: BoundObject<'py, Self::Target>
The smart pointer type to use.
This will usually be [Bound<'py, Target>
], but in special cases [Borrowed<'a, 'py, Target>
] can be
used to minimize reference counting overhead.
Required Methods§
Provided Methods§
Sourcefn type_output() -> TypeInfo
fn type_output() -> TypeInfo
Extracts the type hint information for this type when it appears as a return value.
For example, Vec<u32>
would return List[int]
.
The default implementation returns Any
, which is correct for any type.
For most types, the return value for this method will be identical to that of FromPyObject::type_input
.
It may be different for some types, such as Dict
, to allow duck-typing: functions return Dict
but take Mapping
as argument.
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.