In pyhon3.10, I can run this code snippet without raising any errors:
{}[0]:1
which creates an empty dictionary, and then accesses the 0 key. However, the :1
that follows is what I would consider an invalid syntax. And indeed, if I try to determine the type of the result:
type({}[0]:1)
a syntax error gets raised. A similar behavior occurs whenever I try to work with the result, such as print({}[0]:1)
.
Why does this happen? I am assuming that the interpreter recognizes the expression as not being assigned and does not compile it. And therefore you can run your code with the {}[0]:1
line being present. However, this is not consistent with other syntax errors being raised by different syntactically invalid code (such as 1:1
which raises an error).
{}[0]:1
as a statement is not a syntax error.
It's an annotation where {}[0]
is the thing being annotated and 1
is the annotation. Normally, you would write something like x: int
.
{}[0]
is not an error because it is executed as if on the left-hand side of an assignment.
We can see this by using dis.dis
(this is Python 3.11.2):
>>> dis.dis("{}[0]:1")
0 0 RESUME 0
1 2 SETUP_ANNOTATIONS
4 BUILD_MAP 0
6 POP_TOP
8 LOAD_CONST 0 (0)
10 POP_TOP
12 LOAD_CONST 1 (1)
14 POP_TOP
16 LOAD_CONST 2 (None)
18 RETURN_VALUE
Only when using {}[0]:1
as an expression, it is invalid syntax.
It's a coincidence that you chose {}[0]
on the left-hand side of :
, this does not always work:
>>> print(x):1
File "<stdin>", line 1
print(x):1
^^^^^^^^
SyntaxError: illegal target for annotation
(You should have gotten the same error for 1:1
.)
The corresponding section in the language reference is here: https://docs.python.org/3/reference/simple_stmts.html#annotated-assignment-statements