The sys
module have a function called is_finalizing
. Running help(sys.is_finalizing)
will result in
>>> help(sys.is_finalizing)
Help on built-in function is_finalizing in module sys:
is_finalizing()
Return True if Python is exiting.
What is mean by Python is exiting? The documentation says this,
sys.is_finalizing()
ReturnTrue
if the Python interpreter is shutting down,False
otherwise
I am quite not understand what Python interpreter is shutting down means. Does it mean during the exit
function call, If yes what's the point of sys.is_finalizing()
as it always return False
?. I am trying to understand in which scenario sys.is_finalizing
return True
and in which situation this API is useful?
It's not something most users would ever need, but is_finalizing()
will be True
while the interpreter is shutting down, when it's destroying objects, releasing memory, etc. Knowing that the interpreter is shutting down when an object's __del__()
method is called might let the object decide to take certain actions, or not.
As a quick display in an interactive session:
>>> import sys
>>> class X:
... def __del__(self):
... print(f"__del__: is_finalizing = {sys.is_finalizing()}")
...
>>> x = X()
>>> del x
__del__: is_finalizing = False
>>>
>>> x = X()
>>> sys.is_finalizing()
False
>>> exit()
__del__: is_finalizing = True
Note that, per the Python Data Model, there's no guarantee __del__()
will be called:
It is not guaranteed that
__del__()
methods are called for objects that still exist when the interpreter exits.
(For completeness, note that the example happens to show the object getting deleted immediately as a result of the name being removed with del x
, but that behavior is not guaranteed either.)