Lets assume we have a class in python:
class A(object):
def __del__(self):
print "Del!"
__del__
is called upon deleting/garbage collection of any A
instance.
Is is possible to do the same for a class? I would like to have some method called when the class itself is garbage collected, which I assume is being done at the script exit.
Thanks in advance for any pointers!
Edit: Just as I have expected, everyone is trying to drive me away from using this technique (I would probably make such a comment myself:)), though the question still stands: is it possible?
I want to the the following: I have a class with a static member that needs to be cleaned.
class A(object):
class Meta(type):
def __new__(mcs, name, bases, attrs):
attrs['conn'] = sqlite3.connect( DB_FILE )
return type.__new__(mcs, name, bases, attrs)
__metaclass__ = Meta
I would like A.conn.close()
to be called, but just before the program closes - i.e. when I know that no more instances of A
will be ever created. I know I can do this with atexit
, but this just seems very ugly.
__del__
is already suspicious. It can make objects un-GC-able (in the presence of cycle, the GC doesn't know in which order they must be called since there are propably some dependencies) and since it's non-deterministic, cleanup is better put into a context manager. Why do you think you need this? – Illegitimacy__call__
method to create a new instance of desired class and__del__
method that does what you want – KennSQLObject
orSQLAlchemy
handles DB connections? (i.e. has them open all the time and when they are closed) – Mazuratexit
inMeta::__new__
and hide its "ugliness"? – Laxity