Skip to content

Instantly share code, notes, and snippets.

@nvgoldin
Last active April 25, 2020 10:44
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 nvgoldin/584872810593894929f294baa485e940 to your computer and use it in GitHub Desktop.
Save nvgoldin/584872810593894929f294baa485e940 to your computer and use it in GitHub Desktop.
example of __del__ drawback: order of clearing globals not promised
In [2]: # %load risk_of__del__globals_cleanup.py
...: import gc
...:
...: class GlobalCounter:
...: value = 0
...:
...:
...: class SomeKlass:
...: def __del__(self):
...: print('in SomeKlass __del__')
...: GlobalCounter.value+=1
...:
...: klass = SomeKlass()
...:
...: #GlobalCounter.value+=1
...:
...: #GlobalCounter.value
...:
...: #klass
...:
...:
...:
In [3]: klass
Out[3]: <__main__.SomeKlass at 0x7fa6fa4141f0>
In [4]: GlobalCounter.value+=1
In [5]: GlobalCounter.value
Out[5]: 1
In [6]: klass
Out[6]: <__main__.SomeKlass at 0x7fa6fa4141f0>
In [7]:
Do you really want to exit ([y]/n)? y
in SomeKlass __del__
Exception ignored in: <function SomeKlass.__del__ at 0x7fa6fbee1b80>
Traceback (most recent call last):
File "<ipython-input-2-d7f50334a983>", line 11, in __del__
NameError: name 'GlobalCounter' is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment