I have a class where I create a file object in the constructor. This class also implements a finish() method as part of its interface and in this method I close the file object. The problem is that if I get an exception before this point, the file will not be closed. The class in question has a number of other methods that use the file object. Do I need to wrap all of these in a try finally clause or is there a better approach?
Thanks,
Barry
You could make your class a context-manager, and then wrap object creation and use of that class in a
with-statement. See PEP 343 for details.To make your class a context-manager, it has to implement the methods
__enter__()and__exit__().__enter__()is called when you enter thewith-statement, and__exit__()is guaranteed to be called when you leave it, no matter how.You could then use your class like this:
If you acquire your resources in the constructor, you can make
__enter__()simply returnselfwithout doing anything.__exit__()should just call yourfinish()-method.