Skip to main content

functorial

PyPI - Version PyPI - Python Version


This package started as a small collection of modules for teaching functional programming (FP) concepts to to Ph.D. students in Statistics whose primary experience has been with Python and R, in a highly imperative style. The context for this is a course to help prepare the students for building good software in their research and industrial work. Among other goals, I hope to expose them to different ways of thinking about problems and different approaches to software design. In the FP section of the course, I hope to get them to internalize (at least a bit) the essence of "functional thinking".

Over time, this has developed into a more complete set of FP tools to illustrate a wider range of examples and concepts. These include:

  • Sum types built with Python metaclasses;
  • Standard typeclasses, including Functor, Applicative, Monad, Foldable, Traversable, Alternative, and many others.
  • Higher-kinded data types, including Maybe, Either, List, Dict, NTuple, a variety of trees, IO, Reader, Writer, and State;
  • Monadic do-notation, using Python decorators and generators;
  • Profunctor-based optics, with lenses, prisms, traversals, folds, isos, and their indexed variants;
  • Pure and effectful streams, folds, and transducers; and
  • Monadic parser combinators.

The package also includes a number of example modules that use functorial to tackle a range of problems and applications.

The terminology in the package is strongly Haskell-influenced, but I make changes freely for preference and clarity. For example, I use Some and Nothing for the data constructors of Maybe types, and I use trait in lieu of typeclasses. As part of the course, I use several idealized "thinking languages" for considering problems, solutions, and ideas. One of these (TL1 in the docs) is an idealized hybrid of Haskell, Idris, Unison, and Lean. Comments in this form are often included in the documentation; FP enthusiasts should be able to understand them easily.

The objects here are designed to fit with Python as much as possible. For instance, List inherits from list but has more capabilities, and these types all support pattern matching. SImilarly, decorators are used for do-notation, making it clear and easy to use. And the Resource monad (analogous to ResourceT IO for Haskellers) works well on its own and but also integrates nicely with context managers.

A pure functional style necessarily involves some compromises in Python. For instance, do-notation and traversals must be annotated with the appropriate monad or applicative type, and IO actions are wrapped in functions. Educational value rather than performance is the main design criterion, but I do weight performance and safety as much as possible. For instance, Resource is thread-safe, and some variants of streams are optimized for "fusion" to provide good performance. While this package is designed for educational rather than production use, I have nonetheless found many these tools useful in several other projects.

It's been actually quite illuminating and fun to implement these ideas in Python, and I've benefited from studying many terrific packages in the Haskell ecosystem, notably including optics, streamly, resourcet, and tree-traversals.

This is an evolving, educational project. Some of the API is still settling, some of the dev components have not yet been merged into main, and not everything on the roadmap is implemented yet. Feedback and issues are welcome.

Installation

functorial is available on PyPi. To install, you can do

pip install functorial

or

uv add functorial

in a uv project. This requires Python 3.12+, and later versions are recommended.

Quick taste

Functors and such

from functorial.maybe         import Maybe, Some, Nothing

def a_partial_func(x: int) -> Maybe[float]:
    if x <= 0:
        return Nothing()
    return Some(math.log(x))

match a_partial_func(10):
    case Some(y):
        ...
    case Nothing():
        ...
    case invalid:
        raise SumTypeInvalidCaseException(invalid, Maybe)

Some(3).map(lambda x: x + 1)     # Some(4)
Nothing().map(lambda x: x + 1)   # Nothing()

sequence(List.of(Some(3), Some(2), Some(1)), Maybe)
    # => Some([3, 2, 1])

sequence(List.of(Some(3), Nothing(), Some(1)), Maybe)
    # => Nothing()

t1 = complete_btree(3)
label = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
         "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
         "W", "X", "Y", "Z", "AA", "BB", "CC", "DD", "EE", "FF",]
t1a = t1.map(lambda k: label[k])
print(t1a)
# A
# ├─ C
# │  ├─ G
# │  │  ├─ O
# │  │  └─ N
# │  └─ F
# │     ├─ M
# │     └─ L
# └─ B
#    ├─ E
#    │  ├─ K
#    │  └─ J
#    └─ D
#       ├─ I
#       └─ H

t2 = RoseTree([1, [2, [3], [4], [5]], [6, [7, [8, [9], [10]]]]])
t3 = t2.map(lambda k: k ** 2)
print(t3)
# 1
# ├─ 4
# │  ├─ 9
# │  ├─ 16
# │  └─ 25
# └─ 36
#    └─ 49
#       └─ 64
#          ├─ 81
#          └─ 100

do-notation and effects

@do(Either)
def summed3a():
    x = yield Right(4)
    y = yield Right(10)
    z = yield Right(6)
    return x + y + z

@do(Either)
def summed3b():
    x = yield Right(4)
    y = yield Left(9)    # short circuits
    z = yield Right(10)
    return x + y + z

# sumed3a == Right(20)
# sumed3b == Left(9)

@effect(Either)         # effect makes a function wrapping do
def sum3(mx, my, mz):
    x = yield mx
    y = yield my
    z = yield mz
    return x + y + z

# sum3(Right(4), Left(5), Right(23))  == Left(5)

@effect(List)
def pairs(xs, ys):
    x = yield xs
    y = yield ys
    return (x, y)

# pairs([1, 2], [7, 8, 9])
# == [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9)]

Optics

# Compose lenses with @, act on them with view/over
fst = lens(lambda s: s[0], lambda s, b: (b, s[1]))
snd = lens(lambda s: s[1], lambda s, b: (s[0], b))

view(fst)((1, 2))                     # 1
over(fst @ snd, str)(((1, 2), 3))     # ((1, '2'), 3)

Documentation

Coming Soon

Development

This is a uv-based project. With the repo cloned, you can do

uv sync
uv run pytest

One of the default groups is elpy that installs tools in the venv for use with emacs/elpy.

License

MIT — see LICENSE.

Metadata

Release files for functorial 0.1.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for functorial 0.1.5
File Size Uploaded Provenance Actions
functorial-0.1.5.tar.gz 157.4 kB Without provenance Details for functorial-0.1.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for functorial 0.1.5
File Interpreter ABI Platform Actions
functorial-0.1.5-py3-none-any.whl Python 3 none any Details for functorial-0.1.5-py3-none-any.whl

Total release size: 286.3 kB

Release files / functorial-0.1.5.tar.gz

Download URL functorial-0.1.5.tar.gz
Size 157.4 kB
Tags Source
SHA-256 checksum
How to use checksums
762f9f50804bf7c1e11dd7738220d2174590005d1c0c60945f17a190336353b2
BLAKE2b-256 checksum
How to use checksums
3dfee76049e75f40523d7f246776c31a945605fc6bfc8a917fb6804f778b44e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.24 {"installer":{"name":"uv","version":"0.12.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / functorial-0.1.5-py3-none-any.whl

Download URL functorial-0.1.5-py3-none-any.whl
Size 128.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c090240e21a51b7418960c988375ad373b4850ba59c41cf780f941c8b0ce0c00
BLAKE2b-256 checksum
How to use checksums
02adfe14a0c32c24e571d87d0ac51750d31d913c0aeaeaf4b9f2b676027717c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.24 {"installer":{"name":"uv","version":"0.12.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for functorial 0.1.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page