Skip to content

Instantly share code, notes, and snippets.

@thoas
Created March 5, 2012 11:09
Show Gist options
  • Select an option

  • Save thoas/1977894 to your computer and use it in GitHub Desktop.

Select an option

Save thoas/1977894 to your computer and use it in GitHub Desktop.
import time
def lazy(attr_name):
def lazy_wrapper(fn):
name = attr_name
def _lazyprop(self):
if not hasattr(self, name):
setattr(self, name, fn(self))
return getattr(self, name)
return _lazyprop
return lazy_wrapper
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
class Foo(object):
@property
@lazy('_foo')
def bar(self):
return []
class Bar(object):
@property
def foo(self):
if not hasattr(self, '_foo'):
self._foo = []
return self._foo
@timeit
def f1():
time.sleep(1)
for i in range(1000000):
Foo().bar
print 'f1'
@timeit
def f2():
time.sleep(2)
for i in range(1000000):
Bar().foo
print 'f2'
f1()
f2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment