You can always put any cleanup code you need into a class's __del__
method:
class x:
def __init__(self):
self.thing = get_thing()
def __del__(self):
self.thing.close()
But you shouldn't.
This is a bad idea, for a few reasons. If you're using CPython, having custom __del__
methods means the GC can't break reference cycles. If you're using most other Python implementations, __del__
methods aren't called at predictable times.
This is why you usually put cleanup in explicit close
methods. That's the best you can do within the class itself. It's always up to the user of your class to make sure the close
method gets called, not the class itself.
So, there's no way you can use a with
statement, or anything equivalent, inside your class. But you can make it easier for users of your class to use a with
statement, by making your class into a context manager, as described in roippi's answer, or just by suggesting they use contextlib.closing
in your documentation.