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.
§Setup
To use this feature, add this to your Cargo.toml
:
[dependencies]
## change * to the version you want to use, ideally the latest.
either = "*"
pyo3 = { version = "0.23.0-dev", 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, PyResult, IntoPyObject, types::PyAnyMethods};
fn main() -> PyResult<()> {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
// Create a string and an int in Python.
let py_str = "crab".into_pyobject(py)?;
let py_int = 42i32.into_pyobject(py)?;
// Now convert it to an Either<i32, String>.
let either_str: Either<i32, String> = py_str.extract()?;
let either_int: Either<i32, String> = py_int.extract()?;
Ok(())
})
}
either’s