Optionz documentation¶
Contents:
Introduction¶
A nullable type is needed when there can be an absence of a value. Python uses
None to represent the empty value and Optional[T], i.e., T | None to
represent a nullable T. The other option is to use exceptions, but they are
not expressed as values in the type system, which can be brittle and error-prone.
Python approach is a compromise between the “million dollar mistake”,
in which null is a valid member of every type and the more structured
Maybe[T], that models nullables as a tagged union of Just[T] and Nothing.
This library provides some utility functions for working with Optional values
in a more functional style, inspired by the Maybe monad in Haskell and Rust’s
equivalent Option type.
The main philosophy is that we do not want to introduce a new type like
returns and other similar libraries.
Instead, we want to provide a similar functionality using plain Optional values
so that your code can adopt it incrementally without feeling like an alien in
the Python ecosystem.
As much as I like functional programming and the Maybe monad, I think Python’s
approach is fine and offers most of the same static guarantees. The crucial
difference is that Maybe is a tagged union of two types and Python’s
Optional is a union of sets. They behave mostly the same, but the latter do
not allow nesting: Optional[Optional[T]] flattens to Optional[T], while
Maybe[Maybe[T]] is a whole new type. This is a difference that rarely
matters in practice, and I don’t any anyone is clearly superior to the other.
Installation¶
Install Optionz using pip/uv/poetry whatever you like. For example:
pip install optionz
Optionz consists of a single file, so you can also just copy opt.py to your
project and import it from there. It do not define any new type so there is
no conflict with code that import vs ones that vendorize it.
Usage¶
Import opt and use the functions as needed.
import opt
opt.unwrap(42) # 42
opt.unwrap(None) # raises ValueError
Documentation¶
The documentation is available at https://optionz.rtfd.io/ and includes more examples and explanations of the functions provided by the library.
License¶
Optionz is licensed under the MIT License. See LICENSE for more details.