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

Shane Green shane at umbrellacode.com
Sat Feb 2 12:46:28 CET 2013


with open(path) as input:
     for line in input:
         do(line)

Using with to create reference to opened file returned by open() so it 
could temporarily be assigned to input for the sole purpose of iterating 
its contents never sat very well with me.

  * The context manager returned by open() exists only to create the
    context and return reference "input";
  * the context and code block created by the "with" only exists for
    inner "for" loop's code block to execute in.

Now, given a generator function:

def iterwith(cm):
     with cm as context:
         if context is None:
             context = cm
         for item in context:
             yield item

The previous code can be turned into:

for line in iterwith(open(path)):
     do(line)

So, questions:
     - Is there anything inherently wrong with the idea, or does it exist?
     - Is it a generally useful tool, or are the examples limited to files?
     - Is it possible a more general mechanism could have value, such as:

for line in file with open(path) as file:
     do(line)


The preceding could be leveraged to different effect:

for line in file with locked(path):
write(path + ".out", line)

Or,
     for line in input with nested(open(path),lock,open(opath)) as 
input,locked,output:
         output.write(line)

To revisit the original purpose of "with", this seems to cleanly address 
a very common scenario wherein:

resource = create_resource()
try:
     for item in resource:
         do_something(resource, item)
except:
     raise
finally:
     cleanup()

# Standard with approach...
with create_resource() as resource:
     for item in resource:
         do_something(resource, item)

# With for loop as context...
for item in resource with create_resource() as resource:
     do_something(resource, item)

And, given the translation into statements, maybe even crazy stuff...

[line for line in file with open(path) as file]

J/K, I think.



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


More information about the Python-ideas mailing list