how soon is `__del__` called after reference count drops to zero?

后端 未结 3 1755
不思量自难忘°
不思量自难忘° 2021-01-20 00:00

How soon after the reference count reaches zero is __del__ method called? Does the language promise that it\'s done right away, before any other use code can ex

3条回答
  •  不要未来只要你来
    2021-01-20 00:30

    About the only reason you should ever use __del__ is to help the garbage collector collect more garbage. For instance, if you are implementing something like the ctypes module that attaches shared libraries to the running process, it makes sense to unload those libraries when the last reference to it is collected, to allow its address space to be used for something else.

    For managing other kinds of resources, you almost certainly don't want to have anything to do with the garbage collector. The correct tool for this is context managers. Unlike languages such as C++ or Ada where variable scope is used for RAII, python uses the with statement, along with an object that has an __enter__ and __exit__ method. Many built in python types use this exact mechanism to make sure finalization steps actually occur:

    >>> x = file("foo", 'w')
    >>> x.closed
    False
    >>> with x:
    ...     x.write("bar")
    ... 
    >>> x.closed
    True
    

    This is also valuable from the point of view of the zen of python:

    Explicit is better than implicit.

    because it is clear that cleanup is occuring, it is explicitly written that way. This is much better than the case of cleanup happening "magically" when some hidden variable (the reference count, if one exists, and it doesn't in PyPy or IronPython or Jython) reaches some particular value, maybe.

提交回复
热议问题