Is it possible to overwrite a finalizer registered through weakref.finalize in Python?

  Kiến thức lập trình

I need to automatically cleanup some resources upon garbage collection of the instances of some class. To do so, I have used weakref.finalize(obj, func, /, *args, **kwargs) to register a finalizer in the class constructor (__init__).

My issue is that if some methods are called on the instances, the arguments passed to finalize need to be updated. For this, I called weakref.finalize(obj, func, /, *args, **kwargs) with the new argument values as part of the implementation of those methods.

I was wrongly expecting that calling again weakref.finalize(obj, func, /, *args, **kwargs) for the same object would just overwrite the previously registered finalizer. But instead, it adds it, so that when the garbage collection occurs, both finalizers are called in the reverse order they were registered.

Is there a way to overwrite a registered finalizer, or to unregister it?