Python etc / getattr type annotaions (PEP-526)

Published: 30 March 2021, 18:00

PEP-526, introducing syntax for variable annotations (laded in Python 3.6), allows annotating any valid assignment target:

c.x: int = 0
c.y: int

d = {}
d['a']: int = 0
d['b']: int

The last line is the most interesting one. Adding annotations to an expression suppresses its execution:

d = {}

# fails
# KeyError: 1

# nothing happens
d[1]: 1

Despite being a part of the PEP, it’s not supported by mypy:

$ cat
d = {}
d['a']: int
d['b']: str

$ mypy error: Unexpected type declaration error: Unexpected type declaration note: Revealed type is 'Any' note: Revealed type is 'Any'