Variables are annotated using comments:
x = 3 # type: int
x = negate(x)
x = 'a type-checker might catch this error'
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'
print(typing.get_type_hints(Foo))
# ChainMap({'x': <class 'int'>, 'y': <class 'str'>}, {})
Alternatively, they can be accessed by using the __annotations__
special variable or attribute:
x: int
print(__annotations__)
# {'x': <class 'int'>}
class C:
s: str
print(C.__annotations__)
# {'s': <class 'str'>}