`weakref`回调可以代替`__del__`吗? [英] Can `weakref` callbacks replace `__del__`?
问题描述
有什么障碍阻止 看起来在遥远的过去有人认为 是什么阻止了这种情况发生? 似乎有一些少数用例 更新: https://www.python.org/dev/peps/pep-0442/ =nofollow noreferrer> PEP 442 weakref
__ del __ 做的所有事情都做得很好,例如 finalize
这个调用会在解释器退出之前进行,调用的顺序是明确的,等等)?
weakref
最终会导致从语言中删除 __ del __
。
__ del __
,并且我知道所有的工作似乎至少工作(通常好得多), weakref
回调或<$ c $
__ del __ $ c $的行为c>,以及@ gz和@ user2357112提到的
weakref
的问题,我想知道该语言是否正在朝着制作 __ del __
更可靠,或者使用 weakref
而不是 __ del __
,或者两者兼而有之。
有一些实际的原因 __ del __
仍然存在。一些重要的 weakref
改进,包括 finalize
,都是 python 3.4中的新增功能。所以,用更好的weakrefs替换 __ del __
就不会出现py3k语言中断变化的窗口。
定稿
: $ b
当它是一个选项时,使用
__ del__
方法远不那么麻烦。
无论如何,也许应该在Python 4正在考虑? ;)
Is there any obstacle that prevents weakref
from doing everything that __del__
does but with much stronger guarantees (e.g., finalize
guarantees that the call will be made before the interpreter exits, and the order of calls is well-defined, etc.)?
It seems that in the distant past it was thought that weakref
would eventually lead to the removal of __del__
from the language.
What prevented this from happening?
There seems to be few use cases for __del__
, and all the ones I'm aware of seem to work at least as well (and usually much better) with weakref
callbacks or weakref.finalize
.
Update:
With PEP 442 dramatically improving the behavior of __del__
, and the concerns with weakref
mentioned by @gz and @user2357112, I'm wondering if the language is generally moving towards making __del__
more reliable, or towards using weakref
instead of __del__
, or both.
There's a somewhat pragmatic reason __del__
is still around. Several signficant weakref
improvements, including finalize
, were new in Python 3.4. So, replacing __del__
with better weakrefs missed the window for language breaking changes with py3k.
I think most uses can be replaced by the base weakref functionality, but I'm struck by this observation from Richard Oudkerk in issue 15528 where proposed and implemented finalize
:
[Weakref callbacks] are low level, and working out how to use them correctly requires a bit of head scratching. One must find somewhere to store the weakref till after the referent is dead, and without accidentally keeping the referent alive. Then one must ensure that the callback frees the weakref (without leaving any remnant ref-cycles).
When it is an option, using a
__del__
method is far less hassle.
Anyway, perhaps the question should be brought up again when Python 4 is being considered? ;)
这篇关于`weakref`回调可以代替`__del__`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!