An extra trick to use with this is to memoize the closure so that it is only called once if used multiple times. I use this decorator to convert closures into memoized ones:
def memoize_nullary(f): """ Memoizes a function that takes no arguments. The memoization lasts only as long as we hold a reference to the return value. """ def func(): if not hasattr(func, 'retval'): func.retval = f() return func.retval return func
Comment
An extra trick to use with this is to memoize the closure so that it is only called once if used multiple times. I use this decorator to convert closures into memoized ones:
def memoize_nullary(f):
"""
Memoizes a function that takes no arguments. The memoization lasts only as
long as we hold a reference to the return value.
"""
def func():
if not hasattr(func, 'retval'):
func.retval = f()
return func.retval
return func