[Python-ideas] combine for/with statement

Chris Rebert pyideas at rebertia.com
Wed Aug 3 06:32:01 CEST 2011

On Tue, Aug 2, 2011 at 6:11 PM, Mark McDuff <mmcduff at gmail.com> wrote:
> I find that I am often writing code in the following pattern:
> foo = MyContextManager(*args)
> for bar in my_iter:
>   with foo:
>       # do stuff
> I think it would be much cleaner to be able to write:
> for bar in my_iter with MyContextManager(*args):
>   # do stuff

Some have similarly suggested:

for x in y if foo(x):
   # do stuff

Where would it end? What if someone wants:
    for bar in foo with context if baz:
        # stuff

Even just the Cartesian product of all Python's control structures
with themselves quickly becomes unwieldy.
Down this path lies Perl (particularly its
control-structures-as-statement-suffixes feature).
The simplicity and regularity gained is worth having to suffer 1
additional level of indentation now and then; refactor your code if
the number of levels of indentation in it is becoming problematic.


More information about the Python-ideas mailing list