Skip to the content.

Functions and decorators: Python snippets

Part of 30 Seconds of Python. Source: snippets/functions.py. Every example below is run as a test.

compose

Right-to-left function composition: compose(f, g)(x) == f(g(x)).

def compose(*fns):
    return functools.reduce(lambda f, g: lambda *a, **k: f(g(*a, **k)), fns)
>>> inc_then_double = compose(lambda x: x * 2, lambda x: x + 1)
>>> inc_then_double(5)
12

pipe

Pass a value through functions left to right.

def pipe(value, *fns):
    for fn in fns:
        value = fn(value)
    return value
>>> pipe('  Hello ', str.strip, str.upper, len)
5

once

Decorator: run fn only the first time; later calls return the first result.

def once(fn):
    result = []

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        if not result:
            result.append(fn(*args, **kwargs))
        return result[0]
    return wrapper
>>> @once
... def init():
...     print('setting up')
...     return 42
>>> init()
setting up
42
>>> init()
42

retry

Decorator: retry on the given exceptions with exponential backoff.

def retry(times=3, exceptions=(Exception,), delay=0.0, backoff=2.0):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            wait = delay
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except exceptions:
                    if attempt == times:
                        raise
                    if wait:
                        time.sleep(wait)
                    wait *= backoff
        return wrapper
    return decorator
>>> calls = []
>>> @retry(times=3)
... def flaky():
...     calls.append(1)
...     if len(calls) < 3:
...         raise ConnectionError('try again')
...     return 'ok'
>>> flaky(), len(calls)
('ok', 3)

timed

Decorator: store the last run time (seconds) on wrapper.last_seconds.

def timed(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            wrapper.last_seconds = time.perf_counter() - start
    wrapper.last_seconds = None
    return wrapper
>>> @timed
... def work():
...     return sum(range(1000))
>>> work()
499500
>>> work.last_seconds >= 0
True

memoize

Cache results by arguments. For real code prefer functools.cache.

def memoize(fn):
    cache = {}

    @functools.wraps(fn)
    def wrapper(*args):
        if args not in cache:
            cache[args] = fn(*args)
        return cache[args]
    wrapper.cache = cache
    return wrapper
>>> @memoize
... def fib(n):
...     return n if n < 2 else fib(n - 1) + fib(n - 2)
>>> fib(80)
23416728348467685

ttl_cache

Decorator: cache results for seconds before recomputing.

def ttl_cache(seconds, clock=time.monotonic):
    def decorator(fn):
        cache = {}

        @functools.wraps(fn)
        def wrapper(*args):
            hit = cache.get(args)
            if hit and clock() - hit[0] < seconds:
                return hit[1]
            value = fn(*args)
            cache[args] = (clock(), value)
            return value
        return wrapper
    return decorator
>>> now = [0.0]
>>> @ttl_cache(10, clock=lambda: now[0])
... def stamp():
...     return now[0]
>>> stamp(); now[0] = 5; stamp(); now[0] = 11; stamp()
0.0
0.0
11

curry

Call a function one argument (or a few) at a time.

def curry(fn, arity=None):
    import inspect
    arity = arity or len(inspect.signature(fn).parameters)

    def curried(*args):
        if len(args) >= arity:
            return fn(*args)
        return lambda *more: curried(*args, *more)
    return curried
>>> add3 = curry(lambda a, b, c: a + b + c)
>>> add3(1)(2)(3), add3(1, 2)(3)
(6, 6)

rate_limited

Decorator: space calls so they never exceed calls_per_second.

def rate_limited(calls_per_second, clock=time.monotonic, sleep=time.sleep):
    interval = 1.0 / calls_per_second

    def decorator(fn):
        last = [None]

        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            now = clock()
            if last[0] is not None:
                wait = interval - (now - last[0])
                if wait > 0:
                    sleep(wait)
                    now += wait
            last[0] = now
            return fn(*args, **kwargs)
        return wrapper
    return decorator
>>> t = [0.0]
>>> slept = []
>>> @rate_limited(2, clock=lambda: t[0], sleep=slept.append)
... def ping():
...     return 'pong'
>>> ping(), ping(), slept
('pong', 'pong', [0.5])