In Scala, lazy val is a final variable that is evaluated once at the time of its first access, and not at the time of its declaration. This is essentially a memoized function with no arguments. Here is one of the ways you can implement memoization decorator in Python:
from functools import wraps def memoize(f): @wraps(f) def memoized(*args, **kwargs): key = (args, tuple(sorted(kwargs.items())))
Here's how to use it. With property you can even remove empty parentheses like Scala:
>>> class Foo: ... @property ... @memoize ... def my_lazy_val(self): ... print "calculating" ... return "some expensive value" >>> a = Foo() >>> a.my_lazy_val calculating 'some expensive value' >>> a.my_lazy_val 'some expensive value'
source share