In a python project, I came across the following typo that had been lying dormant for a while in the codebase.
val1: int = 1
val2: int = 2
dict_x: dict[str, int] = {}
# normal dict assignment.
dict_x["key1"] = val1
# typo!! should surely be a syntax error? instead, a nop (?)
dict_x["key2"]: val2
But instead of a syntax error, Python continues silently (and the value of the dict for "key2" is not updated). Plugging this code into the python REPL suggests that the line simply returns None and moves on, and doesn’t modify the dict.
In this case, this behavior (no error occurring) obfuscated a bug that lived in the codebase for a long time.
My suspicion is that this has to do with Python typing, and that this line is being read as a type annotation (and hence, a nop). This explanation only raises more questions, though.
- How can I guarantee that this is what this syntax is doing? I’m concerned there may be dark python syntax I’m unfamiliar with and this line is performing some task I’m unaware of.
- Why are type annotations in this case permitted where clearly neither the string
val2nor the literal number 2 are types?
>Solution :
You can see from the grammar that this is legal because the type annotation is only expected to be an expression, and that’s very broad:
assignment:
| NAME ':' expression ['=' annotated_rhs ]
. . .
This syntax has no bearing the runtime of the code. If the "type" is nonsensical, and the warnings/errors produced will be dependent on the linter being used.