[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

"Data blocks" syntax specification draft

On 23/05/2018 07:47, Steven D'Aprano wrote:
> On Tue, 22 May 2018 18:51:30 +0100, bartc wrote:
>> On 22/05/2018 15:25, Chris Angelico wrote:
> [...]
>>> The tuple has nothing to do with the parentheses, except for the
>>> special case of the empty tuple. It's the comma.
>> No? Take these:
>>    a = (10,20,30)
>>    a = [10,20,30]
>>    a = {10,20,30}
>> If you print type(a) after each, only one of them is a tuple - the one
>> with the round brackets.
> You haven't done enough testing. All you have done is found that "round
> brackets give a tuple, other brackets don't". But you need to test what
> happens if you take away the brackets to be sure that it is the round
> brackets which create the tuple:
>      a = 10, 20, 30  # take away the ()
> You still get a tuple. Taking away the [] and {} also give tuples.

If ... is a comma-separated sequence of (2 or more) expressions, then:

  Enclosed with:             It yields:

  {...} brackets             Set (or dict with key:value items)
  [...] brackets             List
  (...) brackets             Tuple
   ...  (no) brackets        Tuple

Each ... contains commas. But it is what surrounds ..., or that doesn't 
surround ..., that determines what the construction yields. The commas 
are not specific to tuples.

> What happens if you add extra brackets?
>      a = ((10, 20, 30))  # tuple
>      b = ([10, 20, 30])  # list
>      c = ({10, 20, 30})  # set

0 items within the list:

()    Empty tuple
[]    Empty list
{}    Empty dict

1 item within the list

(x)   Yields x
[x]   List of one item
{x}   Set of one item

Because () is used for normal bracketing of expression terms, it 
requires this special form to denote a tuple:

(x,)  Tuple of one item

which can ALSO be used to form one element lists, sets and dicts.

> What if we take away the commas but leave the brackets? If "brackets make
> tuples", then the commas ought to be optional.
>      a = (10 20 30)  # SyntaxError

This will be a syntax error with [] and {} as well. I never said the 
commas were optional, only that the resulting type depends on bracketing 
(see above)

>> The comma is just generally used to separate expressions, it's not
>> specific to tuples.
> Nobody said it was specific to tuples. That would be an absurd thing to
> say. What was said is that the comma is what makes tuples, not the
> brackets.

Suppose you were parsing Python source, had just processed a term of an 
expression, and the next token was a comma. What came before the term 
may have been (, {, [ or nothing. What comes next, would you call:





   readexprsequence(type_of_sequence)     # ie. tuple, list etc

(assume recursive descent parser). Since they have to accomplish the 
same thing (read series of comma-separated terms), what would be the 
advantage in having a separate routine just for tuples?