Skip to content

Instantly share code, notes, and snippets.

@caccavale
Last active July 27, 2018 15:43
Show Gist options
  • Save caccavale/c85b9a8d70c5eb5aa96af78c1f5b6b93 to your computer and use it in GitHub Desktop.
Save caccavale/c85b9a8d70c5eb5aa96af78c1f5b6b93 to your computer and use it in GitHub Desktop.
# Used as a property on field-like things meant to be computed once.
def lazy_property(func):
name = func.__name__
class SuicidalGetter(object):
def __get__(self, instance, owner):
# Replaces itself with the result of instance.func()
setattr(instance, name, func(instance))
return getattr(instance, name) # Oh and return the result
return SuicidalGetter()
# Example:
import time
class Test(object):
@lazy_property
def quick_maths(self):
print("Actually ran this time!")
time.sleep(3)
return 2 + 2
t = Test()
t.quick_maths # Prints and takes 3 seconds
t.quick_maths # Same answer, takes no time
@braddotcoffee
Copy link

I believe in a very "pull yourself up by your bootstraps" approach, so I don't appreciate the title of this property. Can we rename to "cacheing_prop" so there's no negative connotation? I explicitly refuse to include the word "lazy" in my codebase. My developers aren't lazy. I'm not lazy. This is America. There is no place for lazy people

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment