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

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

How to use socket in Python as a context manager?

The socket module is fairly low-level, giving you almost direct access to the C library functionality. You can always use the contextlib.contextmanager decorator to build your own: import socket from contextlib import contextmanager @contextmanager def socketcontext(*args, **kw): s = socket.socket(*args, **kw) try: yield s finally: s.close() with socketcontext(socket.AF_INET, socket.SOCK_DGRAM) as s: or use contextlib.closing() to … 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

Python Multiprocessing Lib Error (AttributeError: __exit__)

In Python 2.x and 3.0, 3.1 and 3.2, multiprocessing.Pool() objects are not context managers. You cannot use them in a with statement. Only in Python 3.3 and up can you use them as such. From the Python 3 multiprocessing.Pool() documentation: New in version 3.3: Pool objects now support the context management protocol – see Context … Read more