Skip to content

Instantly share code, notes, and snippets.

@gmambro
Created March 15, 2016 15:15
Show Gist options
  • Save gmambro/b789b0b12854048689b8 to your computer and use it in GitHub Desktop.
Save gmambro/b789b0b12854048689b8 to your computer and use it in GitHub Desktop.
Python lazy attribute property
class lazy_property(object):
'''
This decorator is meant to be used for lazy evaluation of an object attribute.
The property should represent non-mutable data, as it replaces itself.
Example:
class Configuration(object):
def __init__(self):
config = ConfigParser.ConfigParser()
self._config= config.read('/etc/mytool/site.cfg')
@lazy_property
def verbosity(self):
return self._config.get("common", "verbosity")
@lazy_property
def foobar_url(self):
return self._config.get("foobar", "url")
'''
def __init__(self,fget):
self.fget = fget
self.func_name = fget.__name__
def __get__(self,obj,cls):
if obj is None:
return None
value = self.fget(obj)
setattr(obj,self.func_name,value)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment