[Python-ideas] for line in input with open(path) as input...

Chris Angelico rosuav at gmail.com
Sat Feb 2 14:01:00 CET 2013


On Sat, Feb 2, 2013 at 11:46 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> It's not the *sole* purpose. If all you want it to iterate over the file,
> you can do this:
>
> for line in open(path):
>     ...

If I understand the OP, the issue is that the 'with' creates a name
binding and an indentation level for no purpose; it's like doing this:

f = open(path)
for line in f:
    ...

In that instance, it's possible to inline the function call and use
its result directly; it would be nice to be able to do the same with a
context manager. However, since 'with' isn't an expression, it's not
possible to directly inline the two.

I think the utility function iterwith() is a good - and probably the
best - method; it demands nothing special from the language, and works
quite happily.

ChrisA



More information about the Python-ideas mailing list