typestar

Memoize decorator in Python

Memoization trades memory for speed - standard for expensive pure functions.

def memoize(fn):
    cache = {}

    def wrapper(*args):
        if args not in cache:
            cache[args] = fn(*args)
        return cache[args]

    return wrapper

How it works

  1. Wraps a function in a decorator.
  2. A dict caches each result, keyed by the call's arguments.
  3. Repeat calls with the same arguments return the cached value instantly.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
129
Tokens
40
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 23 seconds.

Type this snippet

Step 4 of 5 in Decorators & closures, step 8 of 53 in Pythonic Python.

← Previous Next →