The classic ``compose``, with all the Pythonic features.
Project description
The classic compose, with all the Pythonic features.
This compose follows the lead of functools.partial and returns callable compose objects which:
have a regular and unambiguous repr,
retain correct signature introspection,
allow introspection of the composed callables,
can be type-checked,
can be weakly referenced,
can have attributes,
will merge when nested, and
can be pickled (if all composed callables can be pickled).
This compose also fails fast with a TypeError if any argument is not callable, or when called with no arguments.
This module also provides an acompose which can compose both regular and async functions.
Versioning
This library’s version numbers follow the SemVer 2.0.0 specification.
Installation
pip install compose
Usage
Import compose:
from compose import compose
All the usual function composition you know and love:
>>> def double(x):
... return x * 2
...
>>> def increment(x):
... return x + 1
...
>>> double_then_increment = compose(increment, double)
>>> double_then_increment(1)
3
Of course any number of functions can be composed:
>>> def double(x):
... return x * 2
...
>>> times_eight = compose(douple, double, double)
>>> times_16 = compose(douple, double, double, double)
We still get the correct signature introspection:
>>> def f(a, b, c=0, **kwargs):
... pass
...
>>> def g(x):
... pass
...
>>> g_of_f = compose(g, f)
>>> import inspect
>>> inspect.signature(g_of_f)
<Signature (a, b, c=0, **kwargs)>
And we can inspect all the composed callables:
>>> g_of_f.functions # in order of execution:
(<function f at 0x4048e6f0>, <function g at 0x405228e8>)
When programmatically inspecting arbitrary callables, we can check if we are looking at a compose instance:
>>> isinstance(g_of_f, compose)
True
We can do all of the above with async functions mixed in by using acompose instead of compose:
from compose import acompose
Recipes
If you want composing zero functions to be the identity function:
def identity(x): return x icompose = partial(compose, identity)
To compose arguments in reverse order:
def rcompose(*functions): return compose(*reversed(functions))
When you need a regular function instead of a callable class instance (for example, to use compose as a method):
def fcompose(*functions): composed = compose(*functions) return lambda *args, **kwargs: composed(*args, **kwargs)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Hashes for compose-1.2.2-py2.py30-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d1447afb8f38b62e9ff8c0385c195cd14e199139e1d68d6e3d278e80dab71c00 |
|
MD5 | 702c990e21c37f253713f46499b9de9b |
|
BLAKE2b-256 | 18bcc5305cba235a0f593d58f203fd06b840e3c7cbada99b8c7ab454d1bb1901 |