Python Language Variables and Attributes


Variables are annotated using comments:

x = 3  # type: int
x = negate(x)
x = 'a type-checker might catch this error'
Python 3.x3.6

Starting from Python 3.6, there is also new syntax for variable annotations. The code above might use the form

x: int = 3

Unlike with comments, it is also possible to just add a type hint to a variable that was not previously declared, without setting a value to it:

y: int

Additionally if these are used in the module or the class level, the type hints can be retrieved using typing.get_type_hints(class_or_module):

class Foo:
    x: int
    y: str = 'abc'

# ChainMap({'x': <class 'int'>, 'y': <class 'str'>}, {})

Alternatively, they can be accessed by using the __annotations__ special variable or attribute:

x: int
# {'x': <class 'int'>}

class C:
    s: str
# {'s': <class 'str'>}