pub trait FromPyObject<'a, 'py>: Sized {
type Error: Into<PyErr>;
const INPUT_TYPE: TypeHint = _;
// Required method
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error>;
// Provided methods
fn type_input() -> TypeInfo { ... }
fn as_local_tz(_: Token) -> Option<Self> { ... }
}Expand description
Extract a type from a Python object.
Normal usage is through the extract methods on Bound, Borrowed and Py, which
forward to this trait.
§Examples
use pyo3::prelude::*;
use pyo3::types::PyString;
Python::attach(|py| {
// Calling `.extract()` on a `Bound` smart pointer
let obj: Bound<'_, PyString> = PyString::new(py, "blah");
let s: String = obj.extract()?;
// Calling `.extract(py)` on a `Py` smart pointer
let obj: Py<PyString> = obj.unbind();
let s: String = obj.extract(py)?;
})Note: Depending on the Python version and implementation, some FromPyObject implementations
may produce a result that borrows into the Python type. This is described by the input lifetime
'a of obj.
Types that must not borrow from the input can use FromPyObjectOwned as a restriction. This
is most often the case for collection types. See its documentation for more details.
§How to implement FromPyObject?
§#[derive(FromPyObject)]
The simplest way to implement FromPyObject for a custom type is to make use of our derive
macro.
use pyo3::prelude::*;
#[derive(FromPyObject)]
struct MyObject {
msg: String,
list: Vec<u32>
}By default this will try to extract each field from the Python object by attribute access, but this can be customized. For more information about the derive macro, its configuration as well as its working principle for other types, take a look at the guide.
In case the derive macro is not sufficient or can not be used for some other reason,
FromPyObject can be implemented manually. In the following types without lifetime parameters
are handled first, because they are a little bit simpler. Types with lifetime parameters are
explained below.
§Manual implementation for types without lifetime
Types that do not contain lifetime parameters are unable to borrow from the Python object, so
the lifetimes of FromPyObject can be elided:
use pyo3::prelude::*;
struct MyObject {
msg: String,
list: Vec<u32>
}
impl FromPyObject<'_, '_> for MyObject {
type Error = PyErr;
fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
Ok(MyObject {
msg: obj.getattr("msg")?.extract()?,
list: obj.getattr("list")?.extract()?,
})
}
}
This is basically what the derive macro above expands to.
§Manual implementation for types with lifetime parameters
For types that contain lifetimes, these lifetimes need to be bound to the corresponding
FromPyObject lifetime. This is roughly how the extraction of a typed Bound is
implemented within PyO3.
use pyo3::prelude::*;
use pyo3::types::PyString;
struct MyObject<'py>(Bound<'py, PyString>);
impl<'py> FromPyObject<'_, 'py> for MyObject<'py> {
type Error = PyErr;
fn extract(obj: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> {
Ok(MyObject(obj.cast()?.to_owned()))
}
}
§Details
Cow<'a, str> is an example of an output type that may or may not borrow from the input
lifetime 'a. Which variant will be produced depends on the runtime type of the Python object.
For a Python byte string, the existing string data can be borrowed for 'a into a
Cow::Borrowed. For a Python Unicode string, the data may have to be reencoded to UTF-8, and
copied into a Cow::Owned. It does not depend on the Python lifetime 'py.
The output type may also depend on the Python lifetime 'py. This allows the output type to
keep interacting with the Python interpreter. See also Bound<'py, T>.
Provided Associated Constants§
Sourceconst INPUT_TYPE: TypeHint = _
const INPUT_TYPE: TypeHint = _
Provides the type hint information for this type when it appears as an argument.
For example, Vec<u32> would be collections.abc.Sequence[int].
The default value is typing.Any, which is correct for any type.
Required Associated Types§
Sourcetype Error: Into<PyErr>
type Error: Into<PyErr>
The type returned in the event of a conversion error.
For most use cases defaulting to PyErr here is perfectly acceptable. Using a custom error type can be used to avoid having to create a Python exception object in the case where that exception never reaches Python. This may lead to slightly better performance under certain conditions.
§Note
Unfortunately Try and thus ? is based on From, not Into, so implementations may
need to use .map_err(Into::into) sometimes to convert a generic Error into a PyErr.
Required Methods§
Sourcefn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error>
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error>
Extracts Self from the bound smart pointer obj.
Users are advised against calling this method directly: instead, use this via
Bound<'_, PyAny>::extract or Py::extract.
Provided Methods§
Sourcefn type_input() -> TypeInfo
fn type_input() -> TypeInfo
Extracts the type hint information for this type when it appears as an argument.
For example, Vec<u32> would return Sequence[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
IntoPyObject::type_output. It may be different for some types, such as Dict,
to allow duck-typing: functions return Dict but take Mapping as argument.
Sourcefn as_local_tz(_: Token) -> Option<Self>
fn as_local_tz(_: Token) -> Option<Self>
Helper used to make a specialized path in extracting DateTime<Tz> where Tz is
chrono::Local, which will accept “naive” datetime objects as being in the local timezone.
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.
Implementations on Foreign Types§
Source§impl FromPyObject<'_, '_> for IpAddr
impl FromPyObject<'_, '_> for IpAddr
Source§impl FromPyObject<'_, '_> for bool
Converts a Python bool to a Rust bool.
impl FromPyObject<'_, '_> for bool
Converts a Python bool to a Rust bool.
Fails with TypeError if the input is not a Python bool.
Source§impl FromPyObject<'_, '_> for char
impl FromPyObject<'_, '_> for char
Source§impl FromPyObject<'_, '_> for i128
impl FromPyObject<'_, '_> for i128
Source§impl FromPyObject<'_, '_> for u64
impl FromPyObject<'_, '_> for u64
Source§impl FromPyObject<'_, '_> for u128
impl FromPyObject<'_, '_> for u128
Source§impl FromPyObject<'_, '_> for usize
impl FromPyObject<'_, '_> for usize
Source§impl FromPyObject<'_, '_> for CString
impl FromPyObject<'_, '_> for CString
Source§impl FromPyObject<'_, '_> for String
Allows extracting strings from Python objects.
Accepts Python str and unicode objects.
impl FromPyObject<'_, '_> for String
Allows extracting strings from Python objects.
Accepts Python str and unicode objects.
Source§impl FromPyObject<'_, '_> for Duration
impl FromPyObject<'_, '_> for Duration
Source§impl FromPyObject<'_, '_> for OsString
impl FromPyObject<'_, '_> for OsString
Source§impl FromPyObject<'_, '_> for PathBuf
impl FromPyObject<'_, '_> for PathBuf
Source§impl FromPyObject<'_, '_> for SystemTime
impl FromPyObject<'_, '_> for SystemTime
Source§impl FromPyObject<'_, '_> for NaiveDate
impl FromPyObject<'_, '_> for NaiveDate
Source§impl FromPyObject<'_, '_> for NaiveDateTime
impl FromPyObject<'_, '_> for NaiveDateTime
Source§impl FromPyObject<'_, '_> for NaiveTime
impl FromPyObject<'_, '_> for NaiveTime
Source§impl FromPyObject<'_, '_> for FixedOffset
impl FromPyObject<'_, '_> for FixedOffset
Source§fn extract(ob: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error>
fn extract(ob: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error>
Convert python tzinfo to rust FixedOffset.
Note that the conversion will result in precision lost in microseconds as chrono offset does not supports microseconds.
const INPUT_TYPE: TypeHint = PyTzInfo::TYPE_HINT
type Error = PyErr
Source§impl FromPyObject<'_, '_> for Local
Available on crate feature chrono-local only.
impl FromPyObject<'_, '_> for Local
chrono-local only.Source§impl FromPyObject<'_, '_> for Utc
impl FromPyObject<'_, '_> for Utc
Source§impl FromPyObject<'_, '_> for Complex<f32>
impl FromPyObject<'_, '_> for Complex<f32>
Source§impl FromPyObject<'_, '_> for Complex<f64>
impl FromPyObject<'_, '_> for Complex<f64>
Source§impl FromPyObject<'_, '_> for Uuid
impl FromPyObject<'_, '_> for Uuid
Source§impl FromPyObject<'_, '_> for NonZeroI8
impl FromPyObject<'_, '_> for NonZeroI8
Source§impl FromPyObject<'_, '_> for NonZeroI16
impl FromPyObject<'_, '_> for NonZeroI16
Source§impl FromPyObject<'_, '_> for NonZeroI32
impl FromPyObject<'_, '_> for NonZeroI32
Source§impl FromPyObject<'_, '_> for NonZeroI64
impl FromPyObject<'_, '_> for NonZeroI64
Source§impl FromPyObject<'_, '_> for NonZeroI128
impl FromPyObject<'_, '_> for NonZeroI128
Source§impl FromPyObject<'_, '_> for NonZeroIsize
impl FromPyObject<'_, '_> for NonZeroIsize
Source§impl FromPyObject<'_, '_> for NonZeroU8
impl FromPyObject<'_, '_> for NonZeroU8
Source§impl FromPyObject<'_, '_> for NonZeroU16
impl FromPyObject<'_, '_> for NonZeroU16
Source§impl FromPyObject<'_, '_> for NonZeroU32
impl FromPyObject<'_, '_> for NonZeroU32
Source§impl FromPyObject<'_, '_> for NonZeroU64
impl FromPyObject<'_, '_> for NonZeroU64
Source§impl FromPyObject<'_, '_> for NonZeroU128
impl FromPyObject<'_, '_> for NonZeroU128
Source§impl FromPyObject<'_, '_> for NonZeroUsize
impl FromPyObject<'_, '_> for NonZeroUsize
Source§impl FromPyObject<'_, '_> for Duration
impl FromPyObject<'_, '_> for Duration
Source§impl FromPyObject<'_, '_> for BigDecimal
impl FromPyObject<'_, '_> for BigDecimal
Source§impl FromPyObject<'_, '_> for Date
impl FromPyObject<'_, '_> for Date
Source§impl FromPyObject<'_, '_> for Decimal
impl FromPyObject<'_, '_> for Decimal
Source§impl FromPyObject<'_, '_> for Duration
impl FromPyObject<'_, '_> for Duration
Source§impl FromPyObject<'_, '_> for ISOWeekDate
impl FromPyObject<'_, '_> for ISOWeekDate
Source§impl FromPyObject<'_, '_> for OffsetDateTime
impl FromPyObject<'_, '_> for OffsetDateTime
Source§impl FromPyObject<'_, '_> for PrimitiveDateTime
impl FromPyObject<'_, '_> for PrimitiveDateTime
Source§impl FromPyObject<'_, '_> for Time
impl FromPyObject<'_, '_> for Time
Source§impl FromPyObject<'_, '_> for Tz
impl FromPyObject<'_, '_> for Tz
Source§impl FromPyObject<'_, '_> for UtcDateTime
impl FromPyObject<'_, '_> for UtcDateTime
Source§impl FromPyObject<'_, '_> for UtcOffset
impl FromPyObject<'_, '_> for UtcOffset
Source§impl<'a> FromPyObject<'a, '_> for &'a str
Available on Py_3_10 or non-Py_LIMITED_API only.
impl<'a> FromPyObject<'a, '_> for &'a str
Py_3_10 or non-Py_LIMITED_API only.Source§impl<'a> FromPyObject<'a, '_> for &'a CStr
Available on Py_3_10 or non-Py_LIMITED_API only.
impl<'a> FromPyObject<'a, '_> for &'a CStr
Py_3_10 or non-Py_LIMITED_API only.Source§impl<'a> FromPyObject<'a, '_> for Cow<'a, str>
impl<'a> FromPyObject<'a, '_> for Cow<'a, str>
Source§impl<'a> FromPyObject<'a, '_> for Cow<'a, CStr>
impl<'a> FromPyObject<'a, '_> for Cow<'a, CStr>
Source§impl<'a> FromPyObject<'a, '_> for Cow<'a, OsStr>
impl<'a> FromPyObject<'a, '_> for Cow<'a, OsStr>
Source§impl<'a> FromPyObject<'a, '_> for Cow<'a, Path>
impl<'a> FromPyObject<'a, '_> for Cow<'a, Path>
Source§impl<'a, 'py> FromPyObject<'a, 'py> for &'a [u8]
impl<'a, 'py> FromPyObject<'a, 'py> for &'a [u8]
Source§impl<'a, 'py> FromPyObject<'a, 'py> for Cow<'a, [u8]>
Special-purpose trait impl to efficiently handle both bytes and bytearray
impl<'a, 'py> FromPyObject<'a, 'py> for Cow<'a, [u8]>
Special-purpose trait impl to efficiently handle both bytes and bytearray
If the source object is a bytes object, the Cow will be borrowed and
pointing into the source object, and no copying or heap allocations will happen.
If it is a bytearray, its contents will be copied to an owned Cow.