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
562
votes
7 answers

Explaining Python's '__enter__' and '__exit__'

I saw this in someone's code. What does it mean? def __enter__(self): return self def __exit__(self, type, value, tb): self.stream.close() Here is the complete code. from __future__ import with_statement#for python2.5…
zjm1126
  • 63,397
  • 81
  • 173
  • 221
313
votes
4 answers

Create a "with" block on several context managers?

Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket. You can acquire them by: with lock: with db_con: with socket: #do stuff But is there a way to do it in one…
olamundo
  • 23,991
  • 34
  • 108
  • 149
94
votes
6 answers

How do I write a null (no-op) contextmanager in Python?

Sometimes I need a dummy context manager that does nothing. It can then be used as a stand-in for a more useful, but optional, context manager. For example: ctx_mgr = if else with ctx_mgr: …
Julian
  • 4,170
  • 4
  • 20
  • 27
80
votes
5 answers

Function acting as both decorator and context manager in Python?

This might be pushing things a little too far, but mostly out of curiosity.. Would it be possible to have a callable object (function/class) that acts as both a Context Manager and a decorator at the same time: def xxx(*args, **kw): # or as a…
Jacob Oscarson
  • 6,363
  • 1
  • 36
  • 46
69
votes
6 answers

In python, is there a good idiom for using context managers in setup/teardown

I am finding that I am using plenty of context managers in Python. However, I have been testing a number of things using them, and I am often needing the following: class MyTestCase(unittest.TestCase): def testFirstThing(self): with…
Danny Staple
  • 7,101
  • 4
  • 43
  • 56
62
votes
4 answers

Asynchronous context manager

I have an asynchronous API which I'm using to connect and send mail to an SMTP server which has some setup and tear down to it. So it fits nicely into using a contextmanager from Python 3's contextlib. Though, I don't know if it's possible write…
freebie
  • 2,161
  • 2
  • 19
  • 36
60
votes
4 answers

StringIO and compatibility with 'with' statement (context manager)

I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below. What I want to do is not have to write to disk with some content that I generate in order…
mpettis
  • 3,222
  • 4
  • 28
  • 35
53
votes
2 answers

__init__ vs __enter__ in context managers

As far as I understand, __init__() and __enter__() methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between. What is the purpose of separating them into two…
max
  • 49,282
  • 56
  • 208
  • 355
53
votes
2 answers

Meaning of "with" statement without "as" keyword

I'm familiar with using python's with statement as a means of ensuring finalization of an object in the event of an exception being thrown. This usually looks like with file.open('myfile.txt') as f: do stuff... which is short-hand for f =…
KDN
  • 1,349
  • 2
  • 14
  • 17
53
votes
3 answers

How to use socket in Python as a context manager?

It seems like it would be only natural to do something like: with socket(socket.AF_INET, socket.SOCK_DGRAM) as s: but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how?
ChaimKut
  • 2,759
  • 3
  • 38
  • 64
52
votes
2 answers

what does yield without value do in context manager

import contextlib import time @contextlib.contextmanager def time_print(task_name): t = time.time() try: yield finally: print task_name, "took", time.time() - t, "seconds." def doproc(): x=1+1 with…
Shuman
  • 3,914
  • 8
  • 42
  • 65
43
votes
5 answers

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

It's typical to require for some task multiple objects which have resources to be explicitly released - say, two files; this is easily done when the task is local to a function using nested with blocks, or - even better - a single with block with…
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
43
votes
4 answers

Getting "NoneType object has no attribute" when using "with ... as" for custom context manager

I wrote a simple context manager in Python for handling unit tests (and to try to learn context managers): class TestContext(object): test_count=1 def __init__(self): self.test_number = TestContext.test_count …
Brian McFarland
  • 9,052
  • 6
  • 38
  • 56
42
votes
5 answers

Handling exceptions inside context managers

I have some code where I try to reach a resource but sometimes it is unavailable, and results in an exception. I tried to implement a retry engine using context managers, but I can't handle the exception raised by the caller inside the __enter__…
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
42
votes
4 answers

Handling instances of a context manager inside another context manager

How should a context manager created inside another context manager be handled in Python? Example: suppose you have class A that acts as a context manager, and class B that also acts as a context manager. But class B instances will have to…
Sahand
  • 2,095
  • 1
  • 19
  • 24
1
2 3
40 41