Either¶
Types, constructors, and combinators for working with one of two exclusive values. See Either concepts for a guided introduction.
Types¶
pyfect.either.Right
dataclass
¶
pyfect.either.Left
dataclass
¶
Constructors¶
pyfect.either.right(value)
¶
Create an Either with a Right value.
pyfect.either.left(value)
¶
Create an Either with a Left value.
Guards¶
pyfect.either.is_right(either)
¶
Return True if the Either is a Right value.
pyfect.either.is_left(either)
¶
Return True if the Either is a Left value.
Mapping¶
pyfect.either.map(f)
¶
Transform the Right value of an Either.
Applies f to the value if Right, passes Left through unchanged.
Example
Source code in src/pyfect/either.py
pyfect.either.map_left(f)
¶
Transform the Left value of an Either.
Applies f to the value if Left, passes Right through unchanged.
Example
Source code in src/pyfect/either.py
pyfect.either.map_both(on_right, on_left)
¶
Transform both the Right and Left values of an Either.
Applies on_right if Right, on_left if Left.
Example
Source code in src/pyfect/either.py
Chaining¶
pyfect.either.flat_map(f)
¶
Chain a computation that itself returns an Either.
Applies f to the Right value and returns the resulting Either directly. If Left, passes it through without calling f.
The output Left type is the union of the input Left type and the Left type returned by f, since either source can produce a Left.
Example
def parse_int(s: str) -> Either[int, str]:
try:
return right(int(s))
except ValueError:
return left("not a number")
pipe(right("42"), flat_map(parse_int)) # Right(value=42)
pipe(right("xx"), flat_map(parse_int)) # Left(value='not a number')
pipe(left("oops"), flat_map(parse_int)) # Left(value='oops')
Source code in src/pyfect/either.py
Combining¶
pyfect.either.zip_with(e1, e2, f)
¶
Combine two Either values using a function.
If both are Right, applies f to their values and returns Right(result). If either is Left, returns the first Left encountered.
Example
zip_with(right("John"), right(25), lambda name, age: {"name": name, "age": age})
# Right(value={'name': 'John', 'age': 25})
zip_with(right("John"), left("no age"), lambda name, age: (name, age))
# Left(value='no age')
zip_with(left("no name"), right(25), lambda name, age: (name, age))
# Left(value='no name')
Source code in src/pyfect/either.py
pyfect.either.all(eithers)
¶
Combine a list or dict of Eithers into a single Either.
If all elements are Right, returns Right containing the collected values. If any element is Left, returns the first Left encountered.
Note
For heterogeneous collections (elements with different Right types), the type checker will not infer the correct type automatically. You should provide an explicit type annotation and suppress the error: