Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

There are several differences you appear to have missed: Context manager get a chance to provide a new object just for the block you are executing. Some context managers just return self there (like file objects do), but, as an example, database connection objects could return a cursor object tied to the current transaction. Context … Read more

How can I use pytest.raises with multiple exceptions?

Pass the exceptions as a tuple to raises: with pytest.raises( (MachineError, NotImplementedError) ): verb = … In the source for pytest, pytest.raises may: catch expected_exception; or pass expected_exception to a RaisesContext instance, which then uses issubclass to check whether the exception was one you wanted. In Python 3, except statements can take a tuple of … 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

Calling __enter__ and __exit__ manually

Your first example is not a good idea: What happens if slave_connection.__enter__ throws an exception: master_connection acquires its resource slave_connection fails DataSync.__enter__ propogates the exception DataSync.__exit__ does not run master_connection is never cleaned up! Potential for Bad Things What happens if master_connection.__exit__ throws an exception? DataSync.__exit__ finished early slave_connection is never cleaned up! Potential for … Read more

Handling instances of a context manager inside another context manager

If you can use the @contextlib.contextmanager decorator your life gets a lot easier: import contextlib @contextlib.contextmanager def internal_cm(): try: print “Entering internal_cm” yield None print “Exiting cleanly from internal_cm” finally: print “Finally internal_cm” @contextlib.contextmanager def external_cm(): with internal_cm() as c: try: print “In external_cm_f”, c yield [c] print “Exiting cleanly from external_cm_f”, c finally: print … Read more

Pythonic way to compose context managers for objects owned by a class

I think contextlib.ExitStack is Pythonic and canonical and it’s the appropriate solution to this problem. The rest of this answer tries to show the links I used to come to this conclusion and my thought process: Original Python enhancement request https://bugs.python.org/issue13585 The original idea + implementation was proposed as a Python standard library enhancement with … Read more

Getting “NoneType object has no attribute” when using “with … as” for custom context manager

Assuming that you need to access the context manager created in the with statement, __enter__ needs to return self. If you don’t need to access it, __enter__ can return whatever you would like. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)