Created
July 1, 2011 20:27
-
-
Save jpablo/1059325 to your computer and use it in GitHub Desktop.
lazy class variables
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
# 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