Skip to content

Structional¤

Immutable structs, controlled randomness, and trees. These are the core tools that are ubiquitous to my style of writing Python. Now available in open source!

Whilst this library does not depend on PyTorch and is broadly applicable across all of Python, the downstream use-case is to make it possible to 'write functional PyTorch'.

This is not a library implementing monads, foldl, and all that magical Haskell stuff.

Installation¤

pip install structional

What's in the box?¤

Struct:

  • is an immutable (frozen) dataclass, making writing safe code easy;
  • is an abstract base class, supporting the stdlib abstractmethod and our own extensions AbstractVar (declaring abstract attributes) and __check_init__ (post-initialization invariants);
  • enforces 'abstract/final rules': in particular that every class can either be subclassed (abstract) or instantiated (concrete) – but not both.

PRNGKey provides access to deterministic randomness.

  • Use-case in ML is perfectly reproducible training runs; awesome for catching bugs.
  • A function need no longer be 'secretly random' because it depends on a background stateful RNG.
  • Call key.some_distribution() to sample from a distribution.
  • Split a key via key.split() to create deterministic but statistically independent new sources of randomness.
  • Keys can only be used once (known as 'linear typing'), to prevent accidental reuse.

tree is a subpackage for manipulating immutable nested structures of tuples, Structs, etc.:

  • tree.map ('functors' for you programming geeks) applies a function to every leaf.
  • tree.replace ('lenses' for the geeks) updates just part of a tree structure, returning a new object out-of-place.