Ben Finney writes:
Ben Finney <ben+pyt...@benfinney.id.au>
Date:
11/24/2015 04:49 AM

To:
python-list@python.org


George Trojan<george.tro...@noaa.gov>  writes:

The following code has bitten me recently:

t=(0,1)
x,y=t if t else 8, 9
print(x, y)
(0, 1) 9
You can simplify this by taking assignment out of the picture::

     >>> t = (0, 1)
     >>> t if t else 8, 9
     ((0, 1), 9)

So that's an “expression list” containing a comma. The reference for
expressions tells us::

     An expression list containing at least one comma yields a tuple. The
     length of the tuple is the number of expressions in the list.

     <URL:https://docs.python.org/3/reference/expressions.html#expression-lists>

I was assuming that a comma has the highest order of evaluation
You were? The operator precedence rules don't even mention comma as an
operator, so why would you assume that?

     
<URL:https://docs.python.org/3/reference/expressions.html#operator-precedence>
What threw me off was the right column in the table stating that binding or tuple display has the highest precedence. Somewhere else there is a statement that a comma makes a tuple, not the parentheses, so the parentheses on the left did not register with me.

that is the expression 8, 9 should make a tuple. Why this is not the
case?
I'm not sure why it's the case that you assumed that

My practical advice: I don't bother trying to remember the complete
operator precedence rules. My simplified precedence rules are:

* ‘+’, ‘-’ have the same precedence.
* ‘*’, ‘/’, ‘//’ have the same precedence.
* For anything else: Use parentheses to explicitly declare the
   precedence I want.

Related: When an expression has enough clauses that it's not *completely
obvious* what's going on, break it up by assigning some sub-parts to
temporary well-chosen descriptive names (not ‘t’).
t was just to illustrate my problem, not the actual code. My lesson is to use parentheses in all cases, maybe with an exception for an obvious y, x = x, y. In my new C code I always write

if (a) {
    f();
}

instead of a valid 2-liner

if (a)
   f();

Too many times I added indented g() call, and since I do more Python than C, the error was not glaringly obvious.

-- \ “It is far better to grasp the universe as it really is than to | `\ persist in delusion, however satisfying and reassuring.” —Carl | _o__) Sagan | Ben Finney
George
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to