Algebraic types for Python (notably providing Sum Types, aka Tagged Unions)
sumtypes provides Algebraic Data Types for Python. The main benefit is the implementation of Sum Types (aka Tagged Unions), which Python doesn’t have any native representation for. Product Types are just objects with multiple attributes.
Documentation is at https://sumtypes.readthedocs.org/
This module uses the attrs library to provide features like attribute validation and defaults.
Decorate your classes to make them a sum type:
import attr from sumtypes import sumtype, constructor, match @sumtype class MyType(object): # constructors specify names for their arguments MyConstructor = constructor('x') AnotherConstructor = constructor('x', 'y') # You can also make use of any feature of the attrs # package by using attr.ib in constructors ThirdConstructor = constructor( one=attr.ib(default=42), two=attr.ib(validator=attr.validators.instance_of(int)))
Then construct them by calling the constructors:
v = MyType.MyConstructor(1) v2 = MyType.AnotherConstructor('foo', 2)
You can get the values from the tagged objects:
assert v.x == 1 assert v2.x == 'foo' assert v2.y == 2
You check the constructor used:
assert type(v) is MyType.MyConstructor
And, like Scala case classes, the constructor type is a subclass of the main type:
assert isinstance(v, MyType)
And the tagged objects support equality:
assert v == MyType.MyConstructor(1) assert v != MyType.MyConstructor(2)
Simple pattern matching is also supported. To write a function over all the cases of a sum type:
@match(MyType) class get_number(object): def MyConstructor(x): return x def AnotherConstructor(x, y): return y def ThirdConstructor(one, two): return one + two assert get_number(v) == 1 assert get_number(v2) == 2
match ensures that all cases are handled. If you really want to write a ‘partial function’ (i.e. one that doesn’t cover all cases), use match_partial.
Over the past few years, the ecosystem of libraries to help with functional programming in Python has exploded. Here are some libraries I recommend:
Release history Release notifications | RSS feed
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Hashes for sumtypes-0.1a6-py2.py3-none-any.whl