Last active
November 30, 2019 10:59
-
-
Save avalentino/8103133 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't
if sys.version_info > (3, 4):
beif sys.version_info >= (3, 4):
?