Last active
August 29, 2015 14:19
-
-
Save ranelpadon/bc2aced9000f6e392509 to your computer and use it in GitHub Desktop.
Python's __del__ has some nasty issues when dealing with objects, list, garbage collection, etc.
This file contains hidden or 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
| # Hypothetical class for saving the Universe. | |
| class Particle: | |
| def __init__(self, name): | |
| self.name = name | |
| print self.name, 'created' | |
| def __del__(self): | |
| print self.name, 'deleted' | |
| # Create new particle objects. | |
| alpha = Particle('alpha') | |
| beta = Particle('beta') | |
| # Insert them into a list. | |
| particles = [alpha, beta] | |
| # After some conditions have been met | |
| # alpha and/or beta must be deleted from the list | |
| # Let's assume we want to delete alpha for now. | |
| # But, surprisingly, the statement below will not execute the alpha.__del__() | |
| del particles[0] | |
| print 'alpha should now be deleted (but the alpha.__del__() is not triggered).\n' \ | |
| 'the "alpha deleted" message should be above this line!' | |
| # The alpha.__del__() only executes if ALL other variables referencing alpha have been deleted. | |
| # Hence, we should delete the original/first alpha variable also. | |
| # Generally, x.__del__ only executes if ALL references related to x are deleted. | |
| # See also: http://www.electricmonk.nl/log/2008/07/07/python-destructor-and-garbage-collection-notes/ | |
| # After the line below, the alpha.__del__() will now be executed (finally!). | |
| del alpha | |
| print 'End of Program.\n' \ | |
| 'Scope of all variables should end at this part.\n' \ | |
| 'The beta variable will be out of the program scope at this moment and will be now deleted automatically.' | |
| # Moral of the story: if you need to force execute x.__del__(), you need to delete all object references to x. | |
| # For example, in the example above you NEED to execute these two statements: | |
| # del particles[0] | |
| # del alpha | |
| # Hence, if you only used an object once, you only need to delete the only reference and | |
| # it will execute the x.__del__() immediately. | |
| # particles = [Particle('alpha'), Particle('beta')] | |
| # del particles[0] will automatically execute the Particle('alpha').__del__() | |
| # because there are no other objects related to it. | |
| # Other related reference: | |
| # http://stackoverflow.com/questions/8907905/python-del-myclass-doesnt-call-object-del |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment