Variables and Attributes

suggest change

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 at module or class level, the type hints can be retrieved using typing.get_type_hints(class_or_module). This assumes import typing.

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

print(typing.get_type_hints(Foo))
# {'x': <class 'int'>, 'y': <class 'str'>}

Alternatively, they can be accessed through the __annotations__ attribute. In the module body, that bare name is not defined; use the module object.

import sys
x: int
print(sys.modules[__name__].__annotations__)
# {'x': <class 'int'>}

class C:
    s: str
print(C.__annotations__)
# {'s': <class 'str'>}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents