Python 3.5+sysfunction
sys.is_finalizing()
interpreter
Returns True once the interpreter is shutting down. Needed in __del__ and background threads to avoid touching half-torn-down modules.
Syntax
sys.is_finalizing()
During shutdown module globals may already be cleared, and __del__ fails with puzzling errors like ''NoneType' object is not callable'. Checking sys.is_finalizing() lets you skip the cleanup. Less obviously, it is still False inside atexit handlers — they run before finalization starts.
Examples
import atexit, sys
class Resource:
def __del__(self):
print('при выходе' if sys.is_finalizing() else 'обычное удаление')
r = Resource()
del r
keep = Resource()
atexit.register(lambda: print('atexit:', sys.is_finalizing()))
print(sys.is_finalizing()) # → False
# → обычное удаление / False / atexit: False / при выходе
See also
Open in the full glossarydocs.python.orgReport an inaccuracy