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) )()

One Response

Subscribe to comments with RSS.

  1. dragon earrings said, on February 11, 2014 at 11:41 am

    I think that this is a very gorgeous blog you have there!
    Would it bother you if I shared your post on twitter along with the link and the header of your page:”Memoization in one line “?

    I entered your site while I was looking for cartilage jewelry and I think that I am
    incredibly fortunate for doing so.
    Best Wishes!!
    The Jewelry for Cartilage Group

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: