Reputation: 21625
Will it cause memory leak if they cannot be cleaned by GC?
Upvotes: 5
Views: 396
Reputation:
It's a standard issue with garbage collection.
It's not about memory leaks, but about the circular references themselves, and about other kinds of resources managed by those objects that may need cleanup. The references create a dependency - you can't delete the referrer until all objects it references are deleted, because it may need to do something with those referred-to objects during its cleanup.
As a contrived example, two objects may each have log files, and during their cleanups may need to write log messages both to their own log file and to the other one. You can't clean up either object first, as by doing so you leave the other object unable to perform its cleanup.
The basic rule is that you can have either reliable destructors (as in C++) or garbage collection (as in Python, Java...), but not both. Though in principle, a static analysis of code (or even a visual inspection in most cases) can tell you which classes might have this circular reference problem.
Upvotes: 7
Reputation: 879671
From the docs for gc.garbage:
Python doesn’t collect such cycles automatically because, in general, it isn’t possible for Python to guess a safe order in which to run the
__del__()
methods. If you know a safe order, you can force the issue by examining the garbage list, and explicitly breaking cycles due to your objects within the list.
Upvotes: 6
Reputation: 5893
It depends on what are You doing in __del__
. If You are using it to handle references to another objects, it may be so.
Some discussion is in docs. More appropriate question is what are You trying to do in __del__
and if it should not be done explicitly somewhere else in the code.
Upvotes: 2