Skip to content

Instantly share code, notes, and snippets.

@ybastide
Created September 10, 2015 13:41
Show Gist options
  • Save ybastide/377ff45191e1234d0590 to your computer and use it in GitHub Desktop.
Save ybastide/377ff45191e1234d0590 to your computer and use it in GitHub Desktop.
Cached property, also for static properties
class cached_property(object):
"""
Decorator that converts a method with a single self argument into a
property cached on the instance, or a class method into a property
cached on the class.
Adapted from django/utils/functional.py.
"""
def __init__(self, func):
self.func = func
def __get__(self, instance, typ):
obj = instance or typ
res = obj.__dict__[self.func.__name__] = self.func(obj)
return res
class Truc(object):
def __init__(self, v):
self.v = v
@cached_property
def chose_statique(self):
return 2+2
@cached_property
def chose_dynamique(self):
return self.v
if __name__ == "__main__":
print Truc.chose_statique
truc = Truc(42)
print truc.chose_dynamique
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment