Search code examples
pythondestructorshutdown

Method that gets called on module deletion in Python


Is there a method that I can add to my module, which will get called when destructing the class?

We have a simple class which has only static member functions and needs to clean up the database connection when unloading the module.

Was hoping there would be a __del__ method either for modules or classes that don't have instances?


Solution

  • When destructing which class? I though you said module?

    Your module lives until the interpreter stops. you can add something to run at that time using the "atexit" module:

    import atexit
    atexit.register(myfunction)
    

    EDIT: Based on your comments.

    Since you don't want it as a destructor, my answer above is correct. Just def another function (or static method if you wish) and register it with the atexit:

    def close_database():
        proceed_to_close()
    
    import atexit
    atexit.register(close_database)
    

    Now a quick note on your definition.

    You said the class doesn't have any instances. So why make it a class? Why not define the functions in the module level instead? modules are first-class objects, cached and imported only once...

    Example, instead of defining database.py:

    class DataBase(object):
        @staticmethod
        def execute_some_query(query):
            code_here()
            some_code()
        @staticmethod
        def close_database():
            proceed_to_close()
    import atexit ; atexit.register(DataBase.close_database)
    

    and using:

    from database import DataBase
    DataBase.execute_some_query(query)
    

    You could do this instead on database.py:

    def execute_some_query(query):
        code_here()
        some_code()
    
    def close_database():
        proceed_to_close()
    import atexit ; atexit.register(close_database)
    

    And use it like this:

    import database
    database.execute_some_query(query)
    

    Or better yet: Use sqlalchemy and avoid all this trouble of creating your own database interface.