Can `weakref` callbacks replace `__del__`?

前端 未结 2 1631
甜味超标
甜味超标 2021-02-12 16:30

Is there any obstacle that prevents weakref from doing everything that __del__ does but with much stronger guarantees (e.g., finalize guarantees that t

2条回答
  •  不思量自难忘°
    2021-02-12 17:16

    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? ;)

提交回复
热议问题