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

Raymond Hettinger python at rcn.com
Sat Feb 21 00:23:45 CET 2009

>    for i in closing(gen(x)):
> if you want the generator closed automatically.

That doesn't really improve on what we have now:

    with closing(gen(x)) as g:
        for i in g:

The proposed syntax puts to much on one-line and
unnecessarily complicates another one of Python's 
fundamental tools.

> 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)):

This looks somewhat unattractive to my eyes.

> Comments?

I think the "problem" you're solving isn't worth solving.


## untested recipe

def closeme(iterable):
 it = iter(iterable)
  for i in it:
   yield i

# doesn't this do this same thing without any interpreter magic?
for i in closeme(gen(x)):

for i in chain.from_iterable(map(closeme, [it1, it2, it3, it4])):

More information about the Python-ideas mailing list