[Python-ideas] with expression
Yann Kaiser
kaiser.yann at gmail.com
Thu Feb 20 22:33:07 CET 2014
The first one could be accomplished like:
x = [line.split() for line in f] with open(thisfile) as f
It would keep f opened while the listcomp is being evaluated. This
makes me think however of a likely accident:
x = (line.split() for line in f) with open('name') as f
next(x) # ValueError: I/O operation on closed file.
This does mirror this mistake though:
with open('name') as f:
return (line.split() for line in f)
When what was meant was:
with open('name') as f:
for line in f:
yield line.split()
(Which is, unfortunately, a __del__ in disguise, which is frowned upon.)
This does raise the question of if we need a "for..in..with" construct
for purposes other than setting a new "highest keyword density" record
:-)
More information about the Python-ideas
mailing list