Skip to content

Instantly share code, notes, and snippets.

@avalentino
Last active November 30, 2019 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avalentino/8103133 to your computer and use it in GitHub Desktop.
Save avalentino/8103133 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.4
import weakref
class Node:
def __init__(self, name):
self.name = name
self._closed = False
print('Node.__init__: {}'.format(self))
def __str__(self):
return 'Node(name="{}", id={}, closed={})'.format(
self.name, id(self), self._closed)
def close(self):
self._closed = True
print('Node.close: {}'.format(self))
def __del__(self):
print('Node.__del__: {}'.format(self))
self.close()
def main():
'''
$ python3.4 -u "weakref_callback.py"
Node.__init__: Node(name="Node01", id=139814978159200, closed=False)
deleting n ...
Node.__del__: Node(name="Node01", id=139814978159200, closed=False)
Node.close: Node(name="Node01", id=139814978159200, closed=True)
weakref finalizer: 139814978159200, <weakref at 0x7f293610e858; dead>
weakref callback:
ref: <weakref at 0x7f293610e858; dead>
ref(): None
<weakref at 0x7f293610e858; dead>
<finalize object at 0x7f29372eb100; dead>
'''
import sys
n = Node('Node01')
def callback(ref):
print('weakref callback:')
print(' ref: {}'.format(ref))
print(' ref(): {}'.format(ref()))
w = weakref.ref(n, callback)
if sys.version_info >= (3, 4):
def finalizer(msg, w):
print('weakref finalizer: {}, {}'.format(msg, w))
f = weakref.finalize(n, finalizer, id(n), w)
print('deleting n ...')
del n
print(w)
if sys.version_info >= (3, 4):
print(f)
if __name__ == '__main__':
main()
@scopatz
Copy link

scopatz commented Dec 24, 2013

Shouldn't if sys.version_info > (3, 4): be if sys.version_info >= (3, 4):?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment