Python Language Type Hints Variables and Attributes

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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'>}

Got any Python Language Question?