Steve D'Aprano wrote:

from io import StringIO  # simulate reading from a file
myfile = StringIO('Is this the room for an argument?')
values = [myfile.read(1) for i in range(33)]
print(''.join(values))

Which is a very contrived and longwinded way to write

   print(myfile.read(33))

and would be much better written that way.

Nobody is denying that it's *possible* to write comprehensions
that rely on order of evaluation. That doesn't mean it's a good
idea to do so.

they also care
about what it contains, and that the comprehension or generator expression
iterates over its argument in a specific order.

I don't think they really care about that. What they actually
care about is that the resulting elements are in the same
*order* as the corresponding source elements. That's a
concept that doesn't inherently have anything to do with
time, so you can think about it without having to visualise
things happening sequentially.

Or at least you can as long as the comprehension doesn't
have anything like 'while' in it. If it does, then the
abstraction isn't just a bit leaky, it has a massive
iceberg-sized hole in the hull.

[format(linenum) + line for (linenum, line) in enumerate(myfile)]

I think that most people would be disturbed if the returned list didn't match
the order of lines in the file.

The order of the elements in the list, yes, but not the
order in time in which they were generated.

If we write:

[process(a) for a in (1, 2, 3)]

then we get ridiculed for being a clueless noobie who
doesn't know how to use comprehensions properly. :-)

(Actually, this being c.l.p, we just get it gently pointed
out that we're uselessly building a list of Nones and
then throwing it away, so it would be much better to
write it as a for-statement instead. But the essence is
the same.)

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to