Skip to content

Repository files navigation

sumtypes

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.

Example

Decorate your classes to make them a sum type:

importattrfromsumtypesimportsumtype, constructor, match@sumtypeclassMyType(object):
# constructors specify names for their argumentsMyConstructor=constructor('x')
AnotherConstructor=constructor('x', 'y')
# You can also make use of any feature of the attrs# package by using attr.ib in constructorsThirdConstructor=constructor(
one=attr.ib(default=42),
two=attr.ib(validator=attr.validators.instance_of(int)))

(attrs package, and attr.ib documentation)

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:

assertv.x==1assertv2.x=='foo'assertv2.y==2

You check the constructor used:

asserttype(v) isMyType.MyConstructor

And, like Scala case classes, the constructor type is a subclass of the main type:

assertisinstance(v, MyType)

And the tagged objects support equality:

assertv==MyType.MyConstructor(1)
assertv!=MyType.MyConstructor(2)

Simple pattern matching is also supported. To write a function over all the cases of a sum type:

@match(MyType)classget_number(object):
defMyConstructor(x): returnxdefAnotherConstructor(x, y): returnydefThirdConstructor(one, two): returnone+twoassertget_number(v) ==1assertget_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.

See Also

Over the past few years, the ecosystem of libraries to help with functional programming in Python has exploded. Here are some libraries I recommend:

  • effect - a library for isolating side-effects
  • pyrsistent - persistent (optimized immutable) data structures in Python
  • toolz - a general library of pure FP functions
  • fn.py - a Scala-inspired set of tools, including a weird lambda syntax, option type, and monads

About

Sum Types, aka Tagged Unions, for Python

Resources

Stars

44 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages