Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't "a:1" be a syntax error in python? [duplicate]

I made a typo in my code that went completely silent syntactically.

dict_args : {"arg1":1,"arg2":2,"arg3":3}
# .... Some more code
some_function(**dict_args)
# .... Some more code

If you haven't noticed it, it's the use of : instead of = when declaring the variable dict_args.

So my question is, does the python syntax : a:1, by itself, hold any meaning ? Or should it hypothetically be considered a syntax error?

like image 735
Imad Avatar asked Oct 16 '22 05:10

Imad


1 Answers

PEP-526 introduced variable annotations, which provide programmers a way to add type information to variables. This allows, among other things, statements like

x: int

to indicate that there is a local variable of type int, without initializing it. In PEP-484 - Acceptable Type Hints, we can see that annotations "must be valid expressions that evaluate without raising exceptions", which your dictionary literal is.

If you look at the Python grammar itself you can see that the expr_stmt and annassign rules make the example you show legal.

If you're using an IDE/other type hinting tools, they should definitely complain about this, but it doesn't break the rules that Python has set up.

like image 55
Patrick Haugh Avatar answered Oct 20 '22 11:10

Patrick Haugh