Skip to content

Instantly share code, notes, and snippets.

@asross
Last active April 9, 2017 17:23
Show Gist options
  • Save asross/28a9072db2a0d3bda4045b37dd4ab779 to your computer and use it in GitHub Desktop.
Save asross/28a9072db2a0d3bda4045b37dd4ab779 to your computer and use it in GitHub Desktop.
Like @Property, but only evaluated once
class cacheprop(object):
def __init__(self, getter): self.getter = getter
def __get__(self, shelf, _):
value = self.getter(shelf)
shelf.__dict__[self.getter.__name__] = value
return value
class Foo():
@cacheprop
def bar(self):
print('baz')
return 'bat'
foo = Foo()
print(foo.bar)
# 'baz'
# 'bat'
print(foo.bar)
# 'bat'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment