Context Manger Gotcha
Context managers are pretty useful when doing an action that involves something of the form:
resource = get_resource() step1() step2() step3() release_resource(resource)
A few places come to mind:
Showing a progress dialog
Granted some of these, namely #2 and #4, don't show up a lot in Python. However, writing your own context manager can be useful. I've used them several times for #1 above.
Writing a context manager is really easy. Essentially just implement enter and exit to a class and use the 'with' keyword to implicitly invoke them. However, there is one caveat to keep in mind, the return value of exit.
There are three required arguments to exit that are either all None or contain information about an exception that was raised inside the 'with' block. Your exit method shouldn't re-raise this exception. Instead, exit should return True if you can handle the exception and do not wish to have it actually raised. However, if you return False then the exception will get automatically raised once exit is completed.
So make sure to always add a return value to your exit methods!
Here's a small list of useful links on context managers:
Published: 05-24-2012 19:27:00