Skip to content

Instantly share code, notes, and snippets.

@dhermes
Created February 18, 2015 17:43
Show Gist options
  • Select an option

  • Save dhermes/36eb807880718703cb9e to your computer and use it in GitHub Desktop.

Select an option

Save dhermes/36eb807880718703cb9e to your computer and use it in GitHub Desktop.
>>> class Foo(object):
... D = []
... def __get__(self, obj, objtype):
... self.D.append((obj, objtype))
... if obj is None:
... return self
... result = 42
... obj.foo = result
... return result
...
>>> class A(object):
... foo = Foo()
... def __init__(self, load_lazily=False):
... if not load_lazily:
... self.foo = None
...
>>> print('Foo.D:', Foo.D)
('Foo.D:', [])
>>> print('A.foo:', A.foo)
('A.foo:', <__main__.Foo object at 0x7f4cdae5c890>)
>>> print('Foo.D:', Foo.D)
('Foo.D:', [(None, <class '__main__.A'>)])
>>> a1 = A()
>>> print('a1.foo:', a1.foo)
('a1.foo:', None)
>>> print('Foo.D:', Foo.D)
('Foo.D:', [(None, <class '__main__.A'>)])
>>> a2 = A(load_lazily=True)
>>> print('a2.foo:', a2.foo)
('a2.foo:', 42)
>>> print('Foo.D:', Foo.D)
('Foo.D:', [(None, <class '__main__.A'>), (<__main__.A object at 0x7f4cdae5c950>, <class '__main__.A'>)])
>>> print('a2.foo:', a2.foo)
('a2.foo:', 42)
>>> print('Foo.D:', Foo.D)
('Foo.D:', [(None, <class '__main__.A'>), (<__main__.A object at 0x7f4cdae5c950>, <class '__main__.A'>)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment