Matthew Moisen
Matthew Moisen

Reputation: 18279

How to specify clean up behavior of an object when it is garbage collected in Python?

Say I have some class that manages a database connection. The user is supposed to call close() on instances of this class so that the db connection is terminated cleanly.

Is there any way in python to get this object to call close() if the interpreter is closed or the object is otherwise picked up by the garbage collector?

Edit: This question assumes the user of the object failed to instantiate it within a with block, either because he forgot or isn't concerned about closing connections.

Upvotes: 1

Views: 681

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 50076

The only way to ensure such a method is called if you don't trust users is using __del__ (docs). From the docs:

Called when the instance is about to be destroyed.

Note that there are lots of issues that make using del tricky. For example, at the moment it is called, the interpreter may be shutting down already - meaning other objects and modules may have been destroyed already. See the notes and warnings for details.


If you really cannot rely on users to be consenting adults, I would prevent them from implicitly avoiding close - don't give them a public open in the first place. Only supply the methods to support with. If anybody explicitly digs into your code to do otherwise, they probably have a good reason for it.

Upvotes: 2

Chris
Chris

Reputation: 136910

Define __enter__ and __exit__ methods on your class and then use it with the with statement:

with MyClass() as c:
    # Do stuff

When the with block ends your __exit__() method will be called automatically.

Upvotes: 1

Related Questions