The most annoying typo error...

Terry Reedy tjreedy at udel.edu
Wed May 7 16:17:34 EDT 2003


> to be an error.  The only reasonably small change I can see which
> would do this would be to make parentheses mandatory for tuples;
> then the above would raise a SyntaxError on parsing, and if you
> did want a tuple you'd have to do
>     x = (foo(y),)

This is a *major* change.  Unlike list/dict brackets and ',',
parentheses are not part of tuple literals.  When not a call operator,
they are priority indicators (as in '(1+2)*3'.  It just happens that
the tuple formation operator ',' has a low very priority, so that ()
is ofter needed to raise its priority in combinations with other
operators. Consider

>>> d={(1,2):3} # () needed to group 1,2 with higher priority :
>>> d[1,2]          # () not needed because [] lower in priority

'=' also has even lower priority, so () is not needed in assignments
either.

> Didn't it used to be this way for one-element tuples?

Perhaps you are thinking of () for an empty tuple?
>>> ()
()

or any literal tuple in a function argument list?
>>> type(1,)
<type 'int'>
>>> type((1,))
<type 'tuple'>

or any add or muplitply of a literal tuple?
>>> 1,+()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad operand type for unary +
>>> (1,)+()
(1,)

>>> 1,*2
  File "<stdin>", line 1
    1,*2
      ^
SyntaxError: invalid syntax
>>> (1,)*2
(1, 1)

Aside from (), these are a matter of using () to indicate a change
from the default priority of 'tupling' versus other operators.  By
stretching a bit, one can even see () as not being part of the
enclosed literal (a null slice) but, again, being something that
changes the default interpretation of the contents.

Terry J. Reedy






More information about the Python-list mailing list