Context manager for Python’s MySQLdb

Previously, MySQLdb connections were context managers. As of this commit on 2018-12-04, however, MySQLdb connections are no longer context managers, and users must explicitly call conn.commit() or conn.rollback(), or write their own context manager, such as the one below. You could use something like this: import config import MySQLdb import MySQLdb.cursors as mc import _mysql_exceptions … Read more

What’s the advantage of using ‘with .. as’ statement in Python?

In order to be equivalent to the with statement version, the code you wrote should look instead like this: f = open(“hello.txt”, “wb”) try: f.write(“Hello Python!\n”) finally: f.close() While this might seem like syntactic sugar, it ensures that you release resources. Generally the world is more complex than these contrived examples and if you forget … Read more

Catching exception in context manager __enter__()

Like this: import sys class Context(object): def __enter__(self): try: raise Exception(“Oops in __enter__”) except: # Swallow exception if __exit__ returns a True value if self.__exit__(*sys.exc_info()): pass else: raise def __exit__(self, e_typ, e_val, trcbak): print “Now it’s running” with Context(): pass To let the program continue on its merry way without executing the context block you … Read more

Alternative to contextlib.nested with variable number of context managers

The new Python 3 contextlib.ExitStack class was added as a replacement for contextlib.nested() (see issue 13585). It is coded in such a way you can use it in Python 2 directly: import sys from collections import deque class ExitStack(object): “””Context manager for dynamic management of a stack of exit callbacks For example: with ExitStack() as … Read more

Break or exit out of “with” statement?

with giving you trouble? Throw more with-able objects at the problem! class fragile(object): class Break(Exception): “””Break out of the with statement””” def __init__(self, value): self.value = value def __enter__(self): return self.value.__enter__() def __exit__(self, etype, value, traceback): error = self.value.__exit__(etype, value, traceback) if etype == self.Break: return True return error Just wrap the expression you’re going … Read more

Understanding the Python with statement and context managers

with doesn’t really replace try/except, but, rather, try/finally. Still, you can make a context manager do something different in exception cases from non-exception ones: class Mgr(object): def __enter__(self): pass def __exit__(self, ext, exv, trb): if ext is not None: print “no not possible” print “OK I caught you” return True with Mgr(): name=”rubicon”/2 #to raise … Read more