[Python-ideas] use context managers for new-style "for" statement

Bruce Frederiksen dangyogi at gmail.com
Fri Feb 20 23:41:33 CET 2009

An idea occurred to me about another way to achieve "new-style" for 
statements that finalize generators properly:

1.  Modify for statements to accept context mangers in addition to 
iterables.  If it gets a context manager, it calls __exit__ when the 
loop terminates for any reason.  Otherwise, it does what it does now.

2.  Add an optional __throw__ method to context managers.  If the 
context manager has a __throw__ method, the for statement forwards 
uncaught exceptions within its body to the context manager.

Thus, you can use:

    for i in closing(gen(x)):

if you want the generator closed automatically.

This would also work for files:

    for line in open(filename):

We might also add a new context manager to contextlib to do both the 
close and the throw.  Maybe call it throwing_to?

    for i in throwing_to(gen(x)):

I would think that throwing_to would also do what closing does.

This somewhat simplifies the common "with closing"/"for" pattern as well 
as adds support for the new close/throw generator methods without any 
new syntax.


-bruce frederiksen

More information about the Python-ideas mailing list