开发者

Disposing of objects with circular references

开发者 https://www.devze.com 2023-04-01 12:03 出处:网络
My design is as follows: __main__ references a a references b b references a a is created and then disposed of from __main__

My design is as follows:

  • __main__ references a
  • a references b
  • b references a
  • a is 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 lo开发者_JAVA技巧cal scope (e.g. of a certain method)

Can this be elegantly performed with with?

What is the alternative?


I recommend either:

  • Using weakref - which is sometimes applicable when circular references are involved
  • or ... just manually disposing of stuff in the order you need - not in __del__ but in an explicit dispose method 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.


What is the alternative?

Do nothing. Until you create millions of circular references like this -- and can prove that this (and only this) is breaking your program -- it doesn't actually matter.


Garbage collector is supposed to handle this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号