On Feb 2, 2013, at 7:16, Shane Green firstname.lastname@example.org wrote:
Thanks Nick. I definitely see your point about iterwith(); have been thinking about that since someone asked where __exit__() would be
If iterwith calls close when the iterator is exhausted, it's useful. In that case, close on __exit__ is only a fallback in cases where you don't exhaust it. If it only has close on __exit__, it's useless, because its the same as not doing anything.
A few months ago I proposed and unproposed a similar extension to generator expression syntax. People suggested multiple versions of an iterwith style function, and I think everyone (including me) agreed that this was a better answer even if you ignore the obvious huge benefit that it doesn't require changing the language.
While your idea isn't identical to mine (in a generator expression, the with would have to come before the for, which doesn't feel as natural as your postfix, and it also breaks the lifting of the outermost iterable, which isn't an issue in the for statement), I think the same thing ends up being true in your case.
for line in iterwith(open(path)):
for line in f with open(path) as f:
I think the first one is more readable. It also doesn't make you repeat the name of an otherwise-unnecessary variable twice. And it doesn't expose that variable to the loop body. If you _want_ to use f, i think you want the explicit with statement for clarity.
The only real advantage to the second is that it immediately closes the file on break, instead of only doing so on normal exit or return. Sometimes that's important, but again, I think in most of those cases you'll want the explicit with scope for clarity.