Created
January 15, 2015 10:09
-
-
Save dex4er/f24ada16ca6be5d2a279 to your computer and use it in GitHub Desktop.
Lazy attribute for Python
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 lazy(object): | |
def __init__(self, default=None, name=None): | |
self.default = default | |
self.name = name | |
def __get__(self, obj, objtype): | |
if obj is None: | |
return self | |
if callable(self.default): | |
default = self.default(obj if obj is not None else objtype) | |
else: | |
default = self.default | |
if self.name is None: | |
return default | |
setattr(obj, self.name, default) | |
return getattr(obj, self.name) | |
class Lazy(object): | |
def __new__(cls, *args, **kwargs): | |
obj = super(Lazy, cls).__new__(cls) | |
for name in dir(obj): | |
attr = getattr(cls, name) | |
if attr.__class__.__name__ == 'lazy': | |
setattr(cls, name, lazy(attr.default, name)) | |
return obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment