Created
February 10, 2014 08:51
-
-
Save ergoithz/8912508 to your computer and use it in GitHub Desktop.
attribute decorator from wheezy.core
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 attribute(object): | |
""" ``attribute`` decorator is intended to promote a | |
function call to object attribute. This means the | |
function is called once and replaced with | |
returned value. | |
>>> class A: | |
... def __init__(self): | |
... self.counter = 0 | |
... @attribute | |
... def count(self): | |
... self.counter += 1 | |
... return self.counter | |
>>> a = A() | |
>>> a.count | |
1 | |
>>> a.count | |
1 | |
""" | |
__slots__ = ('f',) | |
def __init__(self, f): | |
self.f = f | |
def __get__(self, obj, t=None): | |
f = self.f | |
val = f(obj) | |
setattr(obj, f.__name__, val) | |
return val | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod(verbose=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment