Allowing zero-dimensional subscripts

Terry Reedy tjreedy at udel.edu
Fri Jun 9 00:30:39 CEST 2006


<spam.noam at gmail.com> wrote in message 
news:1149801040.936452.26270 at i40g2000cwc.googlegroups.com...
> Hello,
>
> I discovered that I needed a small change to the Python grammar. I
> would like to hear what you think about it.
>
> In two lines:
> Currently, the expression "x[]" is a syntax error.
> I suggest that it will be evaluated like "x[()]", just as "x[a, b]" is
> evaluated like "x[(a, b)]" right now.
>
> In a few more words: Currently, an object can be subscripted by a few
> elements, separated by commas. It is evaluated as if the object was
> subscripted by a tuple containing those elements.

It is not 'as if'.   'a,b' *is* a tuple and the object *is* subcripted by a 
tuple.
Adding () around the non-empty tuple adds nothing except a bit of noise.

>>> dis(compile('x[a,b]','','eval'))
  0           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (a)
              6 LOAD_NAME                2 (b)
              9 BUILD_TUPLE              2
             12 BINARY_SUBSCR
             13 RETURN_VALUE
>>> dis(compile('x[(a,b)]','','eval'))
  0           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (a)
              6 LOAD_NAME                2 (b)
              9 BUILD_TUPLE              2
             12 BINARY_SUBSCR
             13 RETURN_VALUE

Parens around non-empty tuples are only needed for precedence grouping, the 
same as in (a+b)*c.

>I suggest that an
> object will also be subscriptable with no elements at all, and it will
> be evaluated as if the object was subscripted by an empty tuple.

Again, there would be no 'as if' about it.  You are suggesting that the 
parens around a tuple nothing be optional in this particular context. 
While logically possible, Guido decided that tuple nothings should *always* 
be distinguished from other nothings and set off from surrounding code by 
parentheses.  The reason is to avoid ambiguity and catch errors.  I think 
this is overall a good choice.

Terry Jan Reedy






More information about the Python-list mailing list