Skip to content

Instantly share code, notes, and snippets.

@mengzhuo
Last active January 10, 2022 00:24
Show Gist options
  • Save mengzhuo/9809429 to your computer and use it in GitHub Desktop.
Save mengzhuo/9809429 to your computer and use it in GitHub Desktop.
weakref demo
import weakref
class ExpensiveObject(object):
def __init__(self, name):
self.name = name
def __del__(self):
print '(Deleting %s)' % self
obj = ExpensiveObject('Cake')
r = weakref.ref(obj)
p = weakref.proxy(obj)
print 'via obj', obj.name # Cake
print 'via ref', r().name # Cake
print 'via proxy', p.name # Cake
del obj
print 'ref', r() # None
print 'proxy:', p.name # raised
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment