tuples in conditional assignment

Ben Finney ben+python at benfinney.id.au
Mon Nov 23 23:49:04 EST 2015


George Trojan <george.trojan at 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>

> 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’).

-- 
 \     “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




More information about the Python-list mailing list