Can `weakref` callbacks replace `__del__`?

前端 未结 2 1634
甜味超标
甜味超标 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:10

    Answer to the question is really depends on the use case and would also suggest you consider that different Python interpreter implementations do not have the same GC behaviour as CPython.

    PyPy in particular does not call __del__ as-soon-as an object is del-eleted or goes out of scope but 'some time later'. So code that relies on CPython's __del__ behaviour will break on PyPy, and other alternative interpreters.

    What I would recommend is to make use of __enter__ and __exit__ along with the with keyword. For example

    from __future__ import print_function
    
    class MyClass(object):
    
        def __enter__(self):
            print("Entering")
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("Exiting")
    
    # 'with MyClass()' can be used but want to show that
    # code in exit is executed regardless of object
    # life time
    obj = MyClass()
    with obj:
        print("Stuff happening in between")
    

    Result is:

    Entering
    Stuff happening in between
    Exiting
    

    The above order of statements is guaranteed and does not depend on GC behaviour.

    Things that should be done as soon as the code in the with block completes can go in __exit__, such as things that would normally be put in a destructor - clearing file handles, releasing locks and so on.

    A subsequent del on the object, or it going out of scope, will clear the object reference eventually, again depending on interpreter implementation, but things that should be done immediately best not rely on that behaviour.

提交回复
热议问题