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

Yuval Greenfield ubershmekel at gmail.com
Sat Feb 2 16:47:32 CET 2013


On Sat, Feb 2, 2013 at 5:16 PM, Shane Green <shane at umbrellacode.com> wrote:

> Thanks Nick.  I definitely see your point about iterwith(); have been
> thinking about that since someone asked where __exit__() would be invoked.
>
> I meant the following as a more compact way of expressing
>
> for line in file with open(path) as file:
>     process(line)
>
>

This is an interesting idea, though a bit too dense for my taste.


> Indentation levels aren't limited, but flatter is better ;-)
>
>
I really like Golang's solution (defer) which Nick sort of emulates with
ExitStack.

http://docs.python.org/3/library/contextlib.html#contextlib.ExitStack

If ExitStack ever became a language feature, we could write stuff like:


    def f():
        fhand = local open(path)
        process(fhand)
        ghand = local open(path2)
        process(ghand)

# which would be sort of equivalent to

    def g():
        try:
            fhand = None
            ghand = None
            fhand = local open(path)
            process(fhand)
            ghand = local open(path2)
            process(ghand)
        finally:
            if fhand is not None:
                fhand.close()
            if ghand is not None:
                ghand.close()



Yuval
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130202/8e707016/attachment.html>


More information about the Python-ideas mailing list