Python sys.is_finalizing() method



The Python sys.is_finalizing() method that returns True if the Python interpreter is in the process of shutting down and False otherwise. This method is useful for determining if the interpreter is in the finalization phase, which occurs during program exit. It can help developers avoid performing certain operations or accessing resources that may no longer be available during shutdown. This can prevent errors and ensure that cleanup code executes correctly when the interpreter is terminating.

Syntax

Following is the syntax and parameters of Python sys.is_finalizing() method −


sys.is_finalizing()

Parameter

Following is the parameter that sys.is_finalizing() method accepts −

  • object: The object for which you want to get the reference count.
  • Return value

    This method returns the reference count for an object.

    Example 1

    Following is the basic example which checks if the Python interpreter is in the shutdown process and prints an appropriate message −

    
    import sys
    
    if sys.is_finalizing():
        print("Interpreter is shutting down")
    else:
        print("Interpreter is running")
    
    

    Output

    Interpreter is running
    

    Example 2

    In this example a cleanup function is registered using atexit.register(). The sys.is_finalizing() method checks if the interpreter is finalizing before attempting cleanup operations −

    
    import sys
    import atexit
    
    def cleanup():
        if sys.is_finalizing():
            print("Cannot perform cleanup, interpreter is finalizing")
        else:
            print("Performing cleanup")
    
    atexit.register(cleanup)
    
    

    Output

    Performing cleanup
    

    Example 3

    This example defines a class with a destructor (__del__ method) that checks if the interpreter is finalizing before releasing resources −

    
    import sys
    
    class Resource:
        def __del__(self):
            if sys.is_finalizing():
                print("Interpreter is shutting down, releasing resources safely")
            else:
                print("Releasing resources")
    
    resource = Resource()
    
    

    Output

    Interpreter is shutting down, releasing resources safely
    
    python_modules.htm
    Advertisements