with statement and context managers

Nobody nobody at nowhere.com
Wed Aug 3 00:22:42 EDT 2011

On Wed, 03 Aug 2011 12:15:44 +1000, Steven D'Aprano 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
> but to me that looks badly wrong. Surely the spam context manager object
> will exit after the first iteration, and always raise an exception on the
> second? But I don't quite understand context managers enough to be sure.

It depends upon the implementation of MyContextManager. If it's
implemented using the contextlib.contextmanager decorator, then you're
correct: you can only use it once. OTOH, if you implement your own class
with __enter__ and __exit__ methods, you can use the same context manager
object multiple times.

More information about the Python-list mailing list