jbrown
jbrown

Reputation: 7986

How to do something when a python object is destroyed?

How can I perform some cleanup action when a python object is destroyed (for any reason)?

Upvotes: 5

Views: 4534

Answers (2)

user3012759
user3012759

Reputation: 2095

I would recommend you read this: __del__ and think really hard if __del__ will do what you want as most likely it will not... due to peculiar nature of garbage collection.

If you really need to release a resource I recommend using context managers and with statement.

Upvotes: 2

Malik Brahimi
Malik Brahimi

Reputation: 16711

Extend the class of the object:

class MyClass(object):
    def __del__(self):
        object.__del__(self)
        dosomething()

Upvotes: 7

Related Questions