I Might Be Wrong

Memoization in one line

Posted in Python by Leif Ryge on August 27, 2008

The memoization decorator in the Python Decorator Library has served me well, but, after reading stupid lambda tricks, I started thinking about how it could be reduced to a single expression. This is the result:

memoize = lambda f: (lambda d={}: lambda *a: d.setdefault(a, a in d or f(*a)))()

Unlike the original, mine doesn’t catch the case of the memoized function being called with unhashable (mutable) arguments. It doesn’t seem like that is a likely scenario, though.

Here is another version which also works with functions taking named arguments:

memo_with_named_args = lambda f: (lambda d={}: lambda *a,**kw: \
    (lambda *k: d.setdefault(k, k in d or f(*a,**kw)))(tuple(kw.items()),a) )()