Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That wouldn't be the idiomatic "for line in file" loop.


As far as iteration goes, there is no difference between

    for line in open(somepath):
        # stuff
and

    f = open(somepath)
    for line in f:
        # stuff
and the second case would be outright broken if the file just decided to close itself when it stops iterating (as others noted, the developer may now want to append new content, or use file.seek and fly around the file's content).

Not to mention a major issue: `break`. The iterator gets no mention of breaks and the iteration is not terminated at this point (as far as the iterator is concerned, that is) so adding a `break` to your iteration (to stop it early because you've found the data/line you needed in a linear search) would suddenly start leaking file handlers where those were collected beforehand... not good.


For that to work as it does in CPython, the file would have to know it has no name reference attached to it and that its scope is limited to the iteration and that it can close the file when the iteration ends. I'd love to have this idiom supported under other implementations - it's beautiful.


> For that to work as it does in CPython, the file would have to know it has no name reference attached to it and that its scope is limited to the iteration and that it can close the file when the iteration ends.

Which will never happen and really has nothing to do with iteration (or the file object itself)

> I'd love to have this idiom supported under other implementations - it's beautiful.

I disagree on its beauty, but beyond that I can assure you it's never going to be a property of python-the-language.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: