pub trait FromPyObject<'source>: Sized {
    fn extract(ob: &'source PyAny) -> PyResult<Self>;

    fn type_input() -> TypeInfo { ... }
}
Expand description

Extract a type from a Python object.

Normal usage is through the extract methods on Py and PyAny, which forward to this trait.

Examples

use pyo3::prelude::*;
use pyo3::types::PyString;

Python::with_gil(|py| {
    let obj: Py<PyString> = PyString::new(py, "blah").into();

    // Straight from an owned reference
    let s: &str = obj.extract(py)?;

    // Or from a borrowed reference
    let obj: &PyString = obj.as_ref(py);
    let s: &str = obj.extract()?;
})

Note: depending on the implementation, the lifetime of the extracted result may depend on the lifetime of the obj or the prepared variable.

For example, when extracting &str from a Python byte string, the resulting string slice will point to the existing string data (lifetime: 'source). On the other hand, when extracting &str from a Python Unicode string, the preparation step will convert the string to UTF-8, and the resulting string slice will have lifetime 'prepared. Since which case applies depends on the runtime type of the Python object, both the obj and prepared variables must outlive the resulting string slice.

The trait’s conversion method takes a &PyAny argument but is called FromPyObject for historical reasons.

Required Methods

Extracts Self from the source PyObject.

Provided Methods

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 IntoPy::type_output. It may be different for some types, such as Dict, to allow duck-typing: functions return Dict but take Mapping as argument.

Implementations on Foreign Types

Convert python tzinfo to rust FixedOffset.

Note that the conversion will result in precision lost in microseconds as chrono offset does not supports microseconds.

Converts a Python bool to a Rust bool.

Fails with TypeError if the input is not a Python bool.

Allows extracting strings from Python objects. Accepts Python str and unicode objects.

Allows extracting strings from Python objects. Accepts Python str and unicode objects.

Implementors