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


Groups > comp.lang.python > #99293 > unrolled thread

Re: tuples in conditional assignment

Started byBen Finney <ben+python@benfinney.id.au>
First post2015-11-24 15:49 +1100
Last post2015-11-24 15:49 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#99293 — Re: tuples in conditional assignment

FromBen Finney <ben+python@benfinney.id.au>
Date2015-11-24 15:49 +1100
SubjectRe: tuples in conditional assignment
Message-ID<mailman.84.1448340562.2291.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web