Last active
April 9, 2017 17:23
-
-
Save asross/28a9072db2a0d3bda4045b37dd4ab779 to your computer and use it in GitHub Desktop.
Like @Property, but only evaluated once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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