Skip to content

Instantly share code, notes, and snippets.

@pavlin-policar
Created August 24, 2017 11:37
Show Gist options
  • Save pavlin-policar/f602260543a8e359e1b7856c3341ddfc to your computer and use it in GitHub Desktop.
Save pavlin-policar/f602260543a8e359e1b7856c3341ddfc to your computer and use it in GitHub Desktop.
class SomeClass:
class single_execution:
"""Compute property only once and cache the result for further access.
When the property is first accessed, the result is computed, and the
attribute on the instance is replaced with the result. This is
essentially a single execution lazy property.
"""
def __init__(self, method):
self.__method = method
self.__attribute_name = method.__name__
def __get__(self, instance, owner):
result = self.__method(instance)
setattr(instance, self.__attribute_name, result)
return result
@single_execution
def foo(self):
return "some super expensive operation"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment