Allowing zero-dimensional subscripts
Terry Reedy
tjreedy at udel.edu
Thu Jun 8 22:15:37 EDT 2006
<spam.noam at gmail.com> wrote in message
news:1149807149.516004.48590 at f6g2000cwb.googlegroups.com...
> Terry Reedy wrote:
>> > 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.
>>
>
> It doesn't necessarily matter, but technically, it is not "a tuple".
Tell that to the compiler. Here the code again.
>>> 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','','single'))
1 0 LOAD_NAME 0 (a)
3 LOAD_NAME 1 (b)
6 BUILD_TUPLE 2
9 STORE_NAME 2 (x)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
The same exact code to build the tuple a,b.
> The "1, 2" in "x[1, 2]" isn't evaluated according to the same rules as
> in "x = 1, 2"
>>> dis(compile('x[1,2]','','eval'))
0 0 LOAD_NAME 0 (x)
3 LOAD_CONST 2 ((1, 2))
6 BINARY_SUBSCR
7 RETURN_VALUE
>>> dis(compile('x=1,2','','single'))
1 0 LOAD_CONST 3 ((1, 2))
3 STORE_NAME 0 (x)
6 LOAD_CONST 2 (None)
9 RETURN_VALUE
Same exact tuple literal. The tuple rules are the same.
>- for example, you can have "x[1, 2:3:4, ..., 5]", which
> isn't a legal tuple outside of square braces - in fact, it even isn't
> legal inside parens: "x[(1, 2:3:4, ..., 5)]" isn't legal syntax.
Yes, slice and ellipsis literals are only valid directly inside brackets.
And it is definitely worth knowing about them and that this is one place
where a tuple cannot be parenthesized. But once they are accepted, the
slice and ellipsis objects are members of the resulting tuple like any
other.
>>> dis(compile("x[1, 2:3:4, ..., 5]", '','eval'))
0 0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (1)
6 LOAD_CONST 1 (2)
9 LOAD_CONST 2 (3)
12 LOAD_CONST 3 (4)
15 BUILD_SLICE 3
18 LOAD_CONST 4 (Ellipsis)
21 LOAD_CONST 5 (5)
24 BUILD_TUPLE 4
27 BINARY_SUBSCR
28 RETURN_VALUE
So I do not see any point or usefulness in saying that a tuple subcript is
not what it is.
Terry Jan Reedy
More information about the Python-list
mailing list