Skip to content

Instantly share code, notes, and snippets.

@dex4er
Created January 15, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dex4er/f24ada16ca6be5d2a279 to your computer and use it in GitHub Desktop.
Save dex4er/f24ada16ca6be5d2a279 to your computer and use it in GitHub Desktop.
Lazy attribute for Python
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