Tuesday, May 22, 2007

An Aha! Moment

Something clicked in my brain this morning...

lambda is a really neat way to implement lazy evaluation.

cache = {}
def get_from_cache(key, lazy_else=lambda:None):
if key not in cache:
cache[key] = lazy_else()
return cache[key]

>>> obj = get_from_cache('big_list', lambda:function_to_build_big_list())

This is an obviously contrived example (which is slightly broken), but I'm using something similar in a web app, to fetch results from costly SQL queries from memcached.

It simple, elegant, and a good argument for lambda's simple syntax.


Unknown said...

The last line could be written as this instead, which would call your function directly rather than indirectly via a lambda:

>>> obj = get_from_cache('big_list', function_to_build_big_list)

Simon Wittber said...

Yes, its a silly example. I should have used a list comprehension instead, which would have better represented my Aha! moment! :-) (List comprehensions are my actual use-case which led to this...)

Popular Posts