Questions tagged [contextmanager]

A python context manager manages the context of a with statement. A context manager defines enter and exit hooks that get called as the code block under the with statement is entered and exited, respectively.

Python’s creates a runtime context, defined by a context manager. As the code block under the with statement is entered, a __enter__ hook is called on the context manager, and as it is exited (by any means, including exceptions and return statements), the __exit__ hook is called.

Python provides several standard context managers. File objects, for example, can be opened as a context manager, and on exit the file is automatically closed.

Context managers were defined in PEP 343.

613 questions
41
votes
3 answers

Calling __enter__ and __exit__ manually

I've googled calling __enter__ manually but with no luck. So let's imagine I have MySQL connector class that uses __enter__ and __exit__ functions (originally used with with statement) to connect/disconnect from a database. And let's have a class…
Vyktor
  • 20,559
  • 6
  • 64
  • 96
39
votes
2 answers

Python Multiprocessing Lib Error (AttributeError: __exit__)

Am getting this error when using the pool.map(funct, iterable): AttributeError: __exit__ No Explanation, only stack trace to the pool.py file within the module. using in this way: with Pool(processes=2) as pool: pool.map(myFunction, mylist) …
sidewaiise
  • 1,445
  • 3
  • 16
  • 27
38
votes
3 answers

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

I have searched and I'm unable to come up with any good reason to use python's __enter__ /__exit__ rather than __init__ (or __new__ ?) / __del__ . I understand that __enter__ / __exit__ are intended for use with the with statement as context…
BobDoolittle
  • 1,326
  • 1
  • 12
  • 21
38
votes
1 answer

How can I use pytest.raises with multiple exceptions?

I'm testing code where one of two exceptions can be raised: MachineError or NotImplementedError. I would like to use pytest.raises to make sure that at least one of them is raised when I run my test code, but it only seems to accept one exception…
fenceop
  • 1,439
  • 3
  • 18
  • 29
38
votes
5 answers

Encapsulating retries into `with` block

I'm looking to encapsulate logic for database transactions into a with block; wrapping the code in a transaction and handling various exceptions (locking issues). This is simple enough, however I'd like to also have the block encapsulate the…
Michael Waterfall
  • 20,497
  • 27
  • 111
  • 168
36
votes
2 answers

How to safely handle an exception inside a context manager

I think I've read that exceptions inside a with do not allow __exit__ to be call correctly. If I am wrong on this note, pardon my ignorance. So I have some pseudo code here, my goal is to use a lock context that upon __enter__ logs a start datetime…
ThorSummoner
  • 16,657
  • 15
  • 135
  • 147
36
votes
3 answers

Alternative to contextlib.nested with variable number of context managers

We have code that invokes a variable number of context managers depending on runtime parameters: from contextlib import nested, contextmanager @contextmanager def my_context(arg): print("entering", arg) try: yield arg finally: …
ecatmur
  • 152,476
  • 27
  • 293
  • 366
36
votes
7 answers

Catching exception in context manager __enter__()

Is it possible to ensure the __exit__() method is called even if there is an exception in __enter__()? >>> class TstContx(object): ... def __enter__(self): ... raise Exception('Oops in __enter__') ... ... def __exit__(self, e_typ,…
tMC
  • 18,105
  • 14
  • 62
  • 98
34
votes
4 answers

Python nested context manager on multiple lines

In Python 2.6, we used to format our nested context manager that way: with nested( context1, context2 ) as a, b: pass From Python 2.7 and on, nested is deprecated. I've seen lots of example of multiple context manager on a single line,…
Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134
33
votes
1 answer

Return value of __exit__

I understand that __enter__ and __exit__ are used to implement a context manager. if an exception occurs in a with statement, the exception's type, value and traceback are passed to the __exit__ method. __exit__ can handle the…
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
32
votes
2 answers

python 'with' statement, should I use contextlib.closing?

This is from flask tutorial Step 3: from contextlib import closing def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) …
su79eu7k
  • 7,031
  • 3
  • 34
  • 40
31
votes
1 answer

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

I know this was widely discussed, but I still can't find an answer to confirm this: is the with statement identical to calling the same code in a try - (except) -finally block, where whatever one defines in the __exit__ function of the context…
Clara
  • 2,935
  • 6
  • 34
  • 49
30
votes
2 answers

Python: standard function and context manager?

In python, there are many functions that work as both standard functions and context managers. For example open() can be called either as: my_file=open(filename,'w') or with open(filename,'w') as my_file: Both giving you a my_file object that can…
ibrewster
  • 3,482
  • 5
  • 42
  • 54
27
votes
6 answers

Understanding the Python with statement and context managers

I am trying to understand the with statement. I understand that it is supposed to replace the try/except block. Now suppose I do something like this: try: name = "rubicon" / 2 # to raise an exception except Exception as e: print("No, not…
user444997
  • 273
  • 1
  • 3
  • 4
27
votes
1 answer

why does Contextmanager throws a runtime error 'generator didn't stop after throw()'?

In my utility.py I have, @contextmanager def rate_limit_protection(max_tries=3, wait=300): tries = 0 while max_tries > tries: try: yield break except FacebookRequestError as e: …
kamal patwa
  • 429
  • 1
  • 4
  • 9
1
2
3
40 41