Understanding the Python with statement and context managers

The contextlib.contextmanager function decorator provides a handy way of providing a context manager without the need to write a full-fledged ContextManager class of your own (with __enter__ and __exit__ methods, so you don’t have to remember the arguments to the __exit__ method, or that the __exit__ method must return True in order to suppress the … Read more

Is Python *with* statement exactly equivalent to a try – (except) – finally block?

I’m going to put aside mentions of scope, because it’s really not very relevant. According to PEP 343, with EXPR as VAR: BLOCK translates to mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if “as VAR” is present BLOCK … Read more

python ‘with’ statement, should I use contextlib.closing?

Yes, you should be using context.closing(); your own version does something different entirely. The with statement lets a context manager know when a block of code is entered and exited; on exit the context manager is also given access to the exception, if one occurred. File objects use this to automatically close the file when … Read more

Python nested context manager on multiple lines [duplicate]

Python 3.10 and newer Starting from Python 3.10, parentheses are allowed, and you can finally do this: with ( context1 as a, context2 as b ): pass Backslash characters Two or more physical lines may be joined into logical lines using backslash characters (\) (citing the Explicit line joining section) If you want put context … Read more

Return value of __exit__

Yes, that return statement is redundant. Only when type is not None does the return value matter. From the object.__exit__() documentation: If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit … 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

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

How to safely handle an exception inside a context manager

The __exit__ method is called as normal if the context manager is broken by an exception. In fact, the parameters passed to __exit__ all have to do with handling this case! From the docs: object.__exit__(self, exc_type, exc_value, traceback) Exit the runtime context related to this object. The parameters describe the exception that caused the context … Read more

Encapsulating retries into `with` block

Is it possible to repeat the code within a with statement? No. As pointed out earlier in that mailing list thread, you can reduce a bit of duplication by making the decorator call the passed function: def do_work(): … # This is not ideal! @transaction(retries=3) def _perform_in_transaction(): # Atomic DB statements … # called implicitly … Read more

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