Steve D'Aprano wrote:
I take issue with your statement that relying on order of evaluation is always "a very bad idea".

Perhaps what I should say is that relying on side effects in
an expression occurring in a particular order is a bad idea.
Boolean operators are a well-understood special case that
doesn't extend to other expression elements. If you saw

   x = foo(y) + bar(z)

you wouldn't immediately assume it relied critically on
foo being called before bar -- would you?

And especially now that print is a regular function instead of a
statement, it is incredibly useful to stick a print or two in the middle of an
expression for debugging.

That's fine as a temporary hack, but I would never use that
for something the program needs to do as part of its normal
operation.

    # paraphrase, not an actual quote
    "Comprehensions might actually have well-defined semantics in terms
    of for-loops, just as they are documented to have, but we should
    pretend that they don't because some really complicated expressions
    with side-effects can be confusing or buggy."

That's pretty much it, except I would delete "really
complicated". Any reliance on side effects in an expression
is confusing and bug-prone, IMO.

The whole reason to write something as a comprehension is
because you want to express it declaratively. You're saying
"this is the list I want, I don't care how you compute it."

Likewise, the reader should be able to read it as "this is
the list produced, and you *don't have to care* how it
gets computed."

Introducing procedural elements such as "while" into a
comprehension messes that up, because suddenly the reader
*does* have to care about details of how it gets computed.

And those details can be tricky. We've already seen how a
subtle error can creep in when you get a "while" and an
"if" in the wrong order!

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

Reply via email to