Why `a: 2` is not raising a syntax exception in python

Question:

As per title, does anybody know why the python interpreter is not raising exception on the expression

$ python3
Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a : 2
>>> 

?

I’d expect a syntax error

Asked By: r00ta

||

Answers:

Python interprets

a : 2

as a variable annotation (see PEP 526).
Annotations can be used by code analysis tools such as type checkers.

You can access annotations of all variables via module attribute __annotations__

For instance in the code interpreter you’d get

>>> a : 2
>>> __annotations__
{'a': 2}
Answered By: Dima Chubarov
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.