Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #99293

Re: tuples in conditional assignment

From Ben Finney <ben+python@benfinney.id.au>
Newsgroups comp.lang.python
Subject Re: tuples in conditional assignment
Date 2015-11-24 15:49 +1100
Message-ID <mailman.84.1448340562.2291.python-list@python.org> (permalink)
References <mailman.36.1447434002.19880.python-list@python.org> <5653D8BC.1040800@noaa.gov>

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: tuples in conditional assignment Ben Finney <ben+python@benfinney.id.au> - 2015-11-24 15:49 +1100

csiph-web