My design is as follows:
__main__referencesaareferencesbbreferencesaais created and then disposed of from__main__
Thus a and b have circular references. However upon del a I would prefer both a and b disposed of.
I see in many places advice to use Context Managers, and specifically the with statement instead of __del__(). However all the examples I see of with start and end in local scope (e.g. of a certain method)
Can this be elegantly performed with with?
What is the alternative?
I recommend either:
__del__but in an explicitdisposemethod you call at the right time(s)In general, when you know you have circular references, relying on automatic
__del__disposal is not a good idea. It’s brittle – even if you manage to make it work in some case, small changes in dependencies can break it again.