In this article, we'll look at context managers and how they can be used with Python's "with" statements and how to create our own custom co

seen from T1
seen from United States

seen from T1

seen from United States

seen from Greece

seen from Russia
seen from Peru
seen from Germany

seen from United States
seen from China

seen from United States
seen from Malaysia
seen from Singapore

seen from United States
seen from United States
seen from China

seen from United States
seen from China
seen from Germany

seen from United Kingdom
In this article, we'll look at context managers and how they can be used with Python's "with" statements and how to create our own custom co
Python Tutorial: Context Managers - Efficiently Managing Resources #python In this Python Programming Tutorial, we will be learning how to use context managers to properly manage resources.
Context managers inside coroutines
I suspected that context managers inside coroutines should have their __exit__ methods invoked when a coroutine generator is closed. But I wanted to be sure, so I wrote a couple simple programs to test this theory.
def coroutine(fout): with fout: while True: value = (yield) fout.write(value) if __name__ == '__main__': fout = open('test.txt', 'w') gen = coroutine(fout) print 'fout is closed:', fout.closed gen.next() # prime the generator gen.send('hello\n') gen.send('world\n') gen.send('radical\n') gen.close() print 'fout is closed:', fout.closed
This works exactly as expected. The output is:
fout is closed: False fout is closed: True
But what about context managers that you create on your own?
from contextlib import contextmanager @contextmanager def tag(name): print "<%s>" % name try: yield finally: print "</%s>" % name def coroutine(name): with tag(name): while True: value = (yield) print value if __name__ == '__main__': # Normal usage: with tag('h1'): print 'foo ' print 'bar ' print 'basilisk ' # Using with a coroutine: gen = coroutine('h2') gen.next() # prime the generator gen.send('hello') gen.send('world') gen.send('gorgonzola') gen.close()
Again, this works as expected. The output is:
<h1> foo bar basilisk </h1> <h2> hello world gorgonzola </h2>
The key is to make sure that you have a try-finally block in your context manager function. Without it, the closing tag will NOT appear in the output when you close the generator.