tuples in conditional assignment

Steven D'Aprano steve at pearwood.info
Tue Nov 24 06:25:56 EST 2015


On Tue, 24 Nov 2015 02:25 pm, George Trojan wrote:

> The following code has bitten me recently:
> 
>  >>> t=(0,1)
>  >>> x,y=t if t else 8, 9
>  >>> print(x, y)
> (0, 1) 9
> 
> I was assuming that a comma has the highest order of evaluation, that is
> the expression 8, 9 should make a tuple. Why this is not the case?

I'm not sure what sort of answer you are looking for. Why does anything have
the precedence it has?

Making assumptions about the comma's precedence in that way seems unsafe to
me. Consider that function(a, b, c, d) is a function call with four
arguments, NOT a single 4-tuple argument. And:

py> 1, 2, 3 * 2  # expecting (1, 2, 3, 1, 2, 3)
(1, 2, 6)

So there's plenty of evidence that the comma has a very low order of
evaluation, not the highest, and it seems remarkably unsafe to assume the
opposite. Fortunately, it is very simple to test these things out at the
interactive interpreter. I cannot imagine doing any Python programming
without having a Python shell open and ready for me to try out code
snippets.



-- 
Steven




More information about the Python-list mailing list