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

Feedback about page:

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


Type Hints:
* Variables and Attributes

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
67 Type Hints
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve