Is relying on __del__() for cleanup in Python unreliable?

前端 未结 3 1774
抹茶落季
抹茶落季 2020-12-19 02:32

I was reading about different ways to clean up objects in Python, and I have stumbled upon these questions (1, 2) which basically say that cleaning up using __del__()<

3条回答
  •  失恋的感觉
    2020-12-19 02:41

    If you're using CPython, then __del__ fires perfectly reliably and predictably as soon as an object's reference count hits zero. The docs at https://docs.python.org/3/c-api/intro.html state:

    When an object’s reference count becomes zero, the object is deallocated. If it contains references to other objects, their reference count is decremented. Those other objects may be deallocated in turn, if this decrement makes their reference count become zero, and so on.

    You can easily test and see this immediate cleanup happening yourself:

    >>> class Foo:
    ...     def __del__(self):
    ...         print('Bye bye!')
    ... 
    >>> x = Foo()
    >>> x = None
    Bye bye!
    >>> for i in range(5):
    ...     print(Foo())
    ... 
    <__main__.Foo object at 0x7f037e6a0550>
    Bye bye!
    <__main__.Foo object at 0x7f037e6a0550>
    Bye bye!
    <__main__.Foo object at 0x7f037e6a0550>
    Bye bye!
    <__main__.Foo object at 0x7f037e6a0550>
    Bye bye!
    <__main__.Foo object at 0x7f037e6a0550>
    Bye bye!
    >>>
    

    (Though if you want to test stuff involving __del__ at the REPL, be aware that the last evaluated expression's result gets stored as _, which counts as a reference.)

    In other words, if your code is strictly going to be run in CPython, relying on __del__ is safe.

提交回复
热议问题