Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I typoed : instead of = to assign a value to a variable in python. Why didn't this cause a SyntaxError?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

  1. 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.
  2. Why are type annotations in this case permitted where clearly neither the string val2 nor 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading