Module pyo3::either

source ·
Expand description

Conversion to/from either’s Either type to a union of two Python types.

Use of a generic sum type like either is common when you want to either accept one of two possible types as an argument or return one of two possible types from a function, without having to define a helper type manually yourself.


To use this feature, add this to your Cargo.toml:

## change * to the version you want to use, ideally the latest.
either = "*"
pyo3 = { version = "0.21.2", features = ["either"] }

Note that you must use compatible versions of either and PyO3. The required either version may vary based on the version of PyO3.

§Example: Convert a int | str to Either<i32, String>.

use either::Either;
use pyo3::{Python, ToPyObject};

fn main() {
    Python::with_gil(|py| {
        // Create a string and an int in Python.
        let py_str = "crab".to_object(py);
        let py_int = 42.to_object(py);
        // Now convert it to an Either<i32, String>.
        let either_str: Either<i32, String> = py_str.extract(py).unwrap();
        let either_int: Either<i32, String> = py_int.extract(py).unwrap();