Method called when a module is removed in Python

Is there a way that I can add to my module that will be called when the class is destroyed?

We have a simple class that has only static member functions and needs to clear the database connection when the module is unloaded.

Would you like a method __del__for modules or classes that don't have instances?

+5
source share
4 answers

What class is destroyed? I though you said the module?

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

import atexit
atexit.register(myfunction)

EDIT: based on your comments.

, , . ( , ) atexit:

def close_database():
    proceed_to_close()

import atexit
atexit.register(close_database)

.

, . ? ? , ...

, 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)

:

from database import DataBase
DataBase.execute_some_query(query)

database.py:

def execute_some_query(query):
    code_here()
    some_code()

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

:

import database
database.execute_some_query(query)

: sqlalchemy .

+17

, , - __del__. , , __del__, .

: python a module - , ... , . , . __del__ , .

+1

Use the del method:

class Foo:

    def __init__(self):
        print "constructor called."

    def __del__(self):
        print "destructor called."
-1
source

Tested with bpython ...

>>> import atexit
>>> class Test( object ):
...     @staticmethod
...     def __cleanup__():
...         print("cleanup")
...     atexit.register(Test.__cleanup__)
... 
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 6, in Test
NameError: name 'Test' is not defined
-1
source

All Articles