0

The most common syntax of slice objects seems to be int:int:int, and specifically within the [] operator of tuples lists and strs. It makes sense why this syntax can't be used to instantiate a slice,

Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 0:-1:1
  File "<stdin>", line 1
    0:-1:1
    ^
SyntaxError: illegal target for annotation

but when testing to see where the slice object is implicitly handled, it turns out to be in the [] operator:

>>> [].__getitem__(0:-1:1)
  File "<stdin>", line 1
    [].__getitem__(0:-1:1)
                    ^
SyntaxError: invalid syntax
>>> [][0:-1:1]
[]
>>> "".__getitem__(0:-1:1)
  File "<stdin>", line 1
    "".__getitem__(0:-1:1)
                    ^
SyntaxError: invalid synta
>>> ""[0:-1:1]
''

This seems to conflict with the common interpretation that [] is syntactic sugar. What is going on under the hood of []?

thebadgateway
  • 433
  • 1
  • 4
  • 7
  • What do you mean by *"the common interpretation that [] is syntactic sugar"*? What is the evidence for this interpretation being common? `[]` is syntax, not all syntax is sugar. But if you want to say `[]` is syntax sugar for `__getitem__`, then you can also say that `[a:b:c]` is syntax sugar for `__getitem__(slice(a, b, c))`. – kaya3 Sep 11 '22 at 02:06
  • 124 upvotes on [the direct interpretation](https://stackoverflow.com/a/43627489/14927325) – thebadgateway Sep 11 '22 at 02:11
  • 1
    I suggest reading [the documentation](https://docs.python.org/3/reference/expressions.html#subscriptions) if you want something authoritative. The answer you linked to refers to Python 2, and does not appear to be meant to be taken literally as a specification for the meaning of this syntax; certainly, for Python 3 it is not accurate enough to be taken as a specification. As the docs make clear, not all occurrences of `[]` involve a `__getitem__` method; and `[::]` is a different syntactic form with [its own section](https://docs.python.org/3/reference/expressions.html#slicings). – kaya3 Sep 11 '22 at 02:18

1 Answers1

4

The [] operator creates a slice object and passes that to __getitem__:

>>> [1, 2, 3][0:-1:1]
[1, 2]
>>> [1, 2, 3].__getitem__(slice(0, -1, 1))
[1, 2]
Samwise
  • 68,105
  • 3
  • 30
  • 44