Skip to content

Instantly share code, notes, and snippets.

@jpablo
Created July 1, 2011 20:27
Show Gist options
  • Save jpablo/1059325 to your computer and use it in GitHub Desktop.
Save jpablo/1059325 to your computer and use it in GitHub Desktop.
lazy class variables
# first, subclass property:
class ClassProperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
# then, define create_lazy_var
def create_lazy_var(cls,name, func):
private = '_'+name
setattr(cls,private,None)
def get_var(cls):
if getattr(cls,private) is None:
setattr(cls,private,func(cls))
return getattr(cls,private)
get_var = classmethod(get_var)
setattr(cls,name,ClassProperty(get_var))
## example usage
class A(object): pass
create_lazy_var(A,'x',lambda cls: 1)
assert A._x is None
assert A.x == 1
assert A._x == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment