Functional programming for Python
Pragmatic functional programming
Expression aims to be a solid, type-safe, pragmatic, and high performance library for frictionless and practical functional programming in Python 3.10+.
By pragmatic, we mean that the goal of the library is to use simple abstractions to enable you to do practical and productive functional programming in Python (instead of being a Monad tutorial).
Python is a multi-paradigm programming language that also supports functional programming constructs such as functions, higher-order functions, lambdas, and in many ways favors composition over inheritance.
Better Python with F#
Expression tries to make a better Python by providing several functional features inspired by F#. This serves several purposes:
Expression will enable you to work with Python using many of the same programming concepts and abstractions. This enables concepts such as Railway oriented programming (ROP) for better and predictable error handling. Pipelining for workflows, computational expressions, etc.
Expressions evaluate to a value. Statements do something.
F# is a functional programming language for .NET that is succinct (concise, readable, and type-safe) and kind of Pythonic. F# is in many ways very similar to Python, but F# can also do a lot of things better than Python:
You can install the latest expression from PyPI by running pip (or
pip3). Note that expression only works for Python 3.10+.
> pip install expressionTo add Pydantic v2 support, install the pydantic extra:
> pip install expression[pydantic]Expression is designed for ordinary Python code. Start with one of these common needs:
pipe and Seq.Option when a value may be absent.Result when a caller needs an expected failure reason.from expression import pipe
from expression.collections import seq
total = pipe(
[4, 7, 12, 15],
seq.filter(lambda score: score >= 10),
seq.map(lambda score: score * 2),
seq.sum,
)
assert total == 54Learn progressively in the documentation: start with installation, then pipelines, optional values, expected failures, collections, and domain modelling.
|, >>, etc) overloading, this usually confuses more
than it helps.Expression will never provide you with all the features of F# and .NET. We are providing a few of the features we think are useful, and will add more on-demand as we go along.
if-elif-else.None handling.bytearray, array.array and list modules.Expression provides a pipe function similar to |> in F#. We don't want to overload
any Python operators, e.g., | so pipe is a plain old function taking N-arguments,
and will let you pipe a value through any number of functions.
from collections.abc import Callable
from expression import pipe
v = 1
fn1: Callable[[int], int] = lambda x: x + 1
gn1: Callable[[int], int] = lambda x: x * 2
assert pipe(v, fn1, gn1) == gn1(fn1(v))Expression objects (e.g., Some, Seq, Result) also have a pipe method, so you can
dot chain pipelines directly on the object:
from expression import Option, Some
v = Some(1)
fn2: Callable[[Option[int]], Option[int]] = lambda x: x.map(lambda y: y + 1)
gn2: Callable[[Option[int]], Option[int]] = lambda x: x.map(lambda y: y * 2)
assert v.pipe(fn2, gn2) == gn2(fn2(v))So for example with sequences you may create sequence transforming pipelines:
from collections.abc import Callable
from expression.collections import Seq, seq
# Since static type checkes aren't good good at inferring lambda types
mapper: Callable[[int], int] = lambda x: x * 10
predicate: Callable[[int], bool] = lambda x: x > 100
folder: Callable[[int, int], int] = lambda s, x: s + x
xs = Seq.of(9, 10, 11)
ys = xs.pipe(
seq.map(mapper),
seq.filter(predicate),
seq.fold(folder, 0),
)
assert ys == 110Functions may even be composed directly into custom operators:
from expression import compose
from expression.collections import Seq, seq
mapper: Callable[[int], int] = lambda x: x * 10
predicate: Callable[[int], bool] = lambda x: x > 100
folder: Callable[[int, int], int] = lambda s, x: s + x
xs = Seq.of(9, 10, 11)
custom = compose(
seq.map(mapper),
seq.filter(predicate),
seq.fold(folder, 0),
)
ys = custom(xs)
assert ys == 110Expression can be used both with a fluent or functional syntax (or both.)
The fluent syntax uses methods and is very compact. But it might get you into trouble for large pipelines since it's not a natural way of adding line breaks.
from expression.collections import Seq
xs = Seq.of(1, 2, 3)
ys = xs.map(lambda x: x * 100).filter(lambda x: x > 100).fold(lambda s, x: s + x, 0)Note that fluent syntax is probably the better choice if you use mypy for type checking since mypy may have problems inferring types through larger pipelines.
The functional syntax is a bit more verbose but you can easily add new operations on new lines. The functional syntax is great to use together with pylance/pyright.
from expression import pipe
from expression.collections import Seq, seq
mapper: Callable[[int], int] = lambda x: x * 100
xs = Seq.of(1, 2, 3)
ys = pipe(
xs,
seq.map(mapper),
seq.filter(lambda x: x > 100),
seq.fold(lambda s, x: s + x, 0),
)Both fluent and functional syntax may be mixed and even pipe can be used fluently.
from expression.collections import Seq, seq
xs = Seq.of(1, 2, 3).pipe(seq.map(mapper))The Option type is used when a function or method cannot produce a meaningful
output for a given input.
An option value may have a value of a given type, i.e., Some(value), or it might
not have any meaningful value, i.e., Nothing.
from expression import Nothing, Option, Some
def keep_positive(a: int) -> Option[int]:
if a > 0:
return Some(a)
return Nothingfrom typing import Literal
from expression import Ok, Option
def exists(x: Option[int]) -> bool:
match x:
case Option(tag="some"):
return True
case _:
return FalseEffects in Expression is implemented as specially decorated coroutines
(enhanced generators) using
yield, yield from and return to consume or generate optional values:
from collections.abc import Generator
from expression import Some, effect
@effect.option[int]()
def fn3() -> Generator[int, int, int]:
x = yield 42
y = yield from Some(43)
return x + y
xs = fn3()This enables "railway oriented programming",
e.g., if one part of the function yields from Nothing then the function is
side-tracked (short-circuit) and the following statements will never be executed. The
end result of the expression will be Nothing. Thus results from such an option
decorated function can either be Ok(value) or Error(error_value).
from collections.abc import Generator
from expression import Nothing, Some, effect
@effect.option[int]()
def fn4() -> Generator[int, int, int]:
x = yield from Nothing # or a function returning Nothing
# -- The rest of the function will never be executed --
y = yield from Some(43)
return x + y
xs = fn4()
assert xs is NothNo open issues yet, or sync has not completed.