1

Why is the Python interpreter 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.

halfer
  • 19,824
  • 17
  • 99
  • 186
r00ta
  • 98
  • 1
  • 6
  • The syntax is not wrong, its just there is nothing you have done to the a. But syntax is correct. – Mark Maxwell Jun 23 '23 at 09:50
  • think its like a type hinting – Marcus.Aurelianus Jun 23 '23 at 09:55
  • given that it is not a syntax error, what could be the custom usage of such keyword? – r00ta Jun 23 '23 at 09:56
  • a: int or a: SomeType is used to indicate the type hint for the variable a. Syntactically its not wrong. Eg usage: a: int = 2 – Liza Amatya Jun 23 '23 at 09:56
  • It is valid syntax as per the grammar of Python (see [docs](https://docs.python.org/3/reference/simple_stmts.html#annotated-assignment-statements)). An expression is allowed after `:` and `2` is an expression. – ayhan Jun 23 '23 at 10:15

1 Answers1

3

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}
Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76