with statement and context managers
Jack Diederich
jackdied at gmail.com
Tue Aug 2 22:28:15 EDT 2011
On Tue, Aug 2, 2011 at 10:15 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> I'm not greatly experienced with context managers and the with statement, so
> I would like to check my logic.
>
> Somebody (doesn't matter who, or where) stated that they frequently use this
> idiom:
>
> spam = MyContextManager(*args)
> for ham in my_iter:
> with spam:
> # do stuff
>
[snip]
> # Simple example using built-in file context manager.
>
>>>> spam = open('aaa')
>>>> for ham in range(5):
> ... with spam:
> ... print ham
> ...
> 0
> Traceback (most recent call last):
> File "<stdin>", line 2, in <module>
> ValueError: I/O operation on closed file
file_context = lambda: open('aaa')
for i in range(3):
with file_context():
print "hello"
.. but if the context is short it is clearer and time saving to _not_
alias it. If the context is sufficiently complicated then it is worth
it to make the complex code into a first class context manager -
contextlib.contextmanager makes this very easy and extremely readable.
-Jack
More information about the Python-list
mailing list