tyrion

lazy.py

Sep 23rd, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. class lazy(object):
  2.     """
  3.    Normal approach::
  4.  
  5.      >>> class Test(object):
  6.      ...     @property
  7.      ...     def attr(self):
  8.      ...         print "attr property"
  9.      ...         if not hasattr(self, '_attr'):
  10.      ...             print "expensive load"
  11.      ...             self._attr = 42
  12.      ...         return self._attr
  13.      >>> t = Test()
  14.      >>> t.attr
  15.      attr property
  16.      expensive load
  17.      42
  18.      >>> t.attr
  19.      attr property
  20.      42
  21.      >>> vars(t)
  22.      {'_attr': 42}
  23.  
  24.    @lazy approach:
  25.  
  26.      >>> class Test(object):
  27.              @lazy
  28.              def attr(self):
  29.                  print "expensive load"
  30.                  return 42
  31.  
  32.      >>> t = Test()
  33.      >>> vars(t)
  34.      {}
  35.      >>> t.attr
  36.      expensive load
  37.      42
  38.      >>> vars(t)
  39.      {'attr': 42}
  40.      >>> t.attr
  41.      42
  42.    """
  43.        
  44.     __slots__ = ['setup']
  45.  
  46.     def __init__(self, setup):
  47.         self.setup = setup
  48.  
  49.     def __get__(self, obj, type):
  50.         if obj is None:
  51.             return self
  52.         s = self.setup(obj)
  53.         setattr(obj, self.setup.__name__, s)
  54.         return s
Advertisement
Add Comment
Please, Sign In to add comment