"Jim Jewett" email@example.com wrote in news:firstname.lastname@example.org:
As a strawman proposal:
deletes = [(obj.__del__.cycle, obj) for obj in cycle if hasattr(obj, "__del__") and
hasattr(obj.__del__, "cycle")] deletes.sort() for (cycle, obj) in deletes: obj.__del__()
Lightweight __del__ methods (such as most resource managers) could set the cycle attribute to True, and thereby ensure that they won't cause unbreakable cycles. Fancier object frameworks could use different values for the cycle attribute. Any object whose __del__ is not annotated will still be at least as likely to get finalized as it is
That doesn't look right to me.
Surely if you have a cycle what you want to do is to pick just *one* of the objects in the cycle and break the link which makes it participate in the cycle. That should be sufficient to cause the rest of the cycle to collapse with __del__ methods being called from the normal refcounting mechanism.
So something like this:
for obj in cycle: if hasattr(obj, "__breakcycle__"): obj.__breakcycle__() break
Every object which knows it can participate in a cycle then has the option of defining a method which it can use to tear down the cycle. e.g. by releasing the resource and then deleting all of its attributes, but no guarantees are made over which obj has this method called. An object with a __breakcycle__ method would have to be extra careful as its methods could still be called after it has broken the cycle, but it does mean that the responsibilities are in the right place (i.e. defining the method implies taking that into account).