Debian Codegraph @

docs/source/type_inference_and_annotations.rst

raw
1 .. _type-inference-and-annotations:
2
3 Type inference and type annotations
4 ===================================
5
6 Type inference
7 **************
8
9 For most variables, if you do not explicitly specify its type, mypy will
10 infer the correct type based on what is initially assigned to the variable.
11
12 .. code-block:: python
13
14 # Mypy will infer the type of these variables, despite no annotations
15 i = 1
16 reveal_type(i) # Revealed type is "builtins.int"
17 l = [1, 2]
18 reveal_type(l) # Revealed type is "builtins.list[builtins.int]"
19
20
21 .. note::
22
23 Note that mypy will not use type inference in dynamically typed functions
24 (those without a function type annotation) — every local variable type
25 defaults to ``Any`` in such functions. For more details, see :ref:`dynamic-typing`.
26
27 .. code-block:: python
28
29 def untyped_function():
30 i = 1
31 reveal_type(i) # Revealed type is "Any"
32 # 'reveal_type' always outputs 'Any' in unchecked functions
33
34 .. _explicit-var-types:
35
36 Explicit types for variables
37 ****************************
38
39 You can override the inferred type of a variable by using a
40 variable type annotation:
41
42 .. code-block:: python
43
44 x: int | str = 1
45
46 Without the type annotation, the type of ``x`` would be just ``int``. We
47 use an annotation to give it a more general type ``int | str`` (this
48 type means that the value can be either an ``int`` or a ``str``).
49
50 The best way to think about this is that the type annotation sets the type of
51 the variable, not the type of the expression. For instance, mypy will complain
52 about the following code:
53
54 .. code-block:: python
55
56 x: int | str = 1.1 # error: Incompatible types in assignment
57 # (expression has type "float", variable has type "int | str")
58
59 .. note::
60
61 To explicitly override the type of an expression you can use
62 :py:func:`cast(\<type\>, \<expression\>) <typing.cast>`.
63 See :ref:`casts` for details.
64
65 Note that you can explicitly declare the type of a variable without
66 giving it an initial value:
67
68 .. code-block:: python
69
70 # We only unpack two values, so there's no right-hand side value
71 # for mypy to infer the type of "cs" from:
72 a, b, *cs = 1, 2 # error: Need type annotation for "cs"
73
74 rs: list[int] # no assignment!
75 p, q, *rs = 1, 2 # OK
76
77 Explicit types for collections
78 ******************************
79
80 The type checker cannot always infer the type of a list or a
81 dictionary. This often arises when creating an empty list or
82 dictionary and assigning it to a new variable that doesn't have an explicit
83 variable type. Here is an example where mypy can't infer the type
84 without some help:
85
86 .. code-block:: python
87
88 l = [] # Error: Need type annotation for "l"
89
90 In these cases you can give the type explicitly using a type annotation:
91
92 .. code-block:: python
93
94 l: list[int] = [] # Create empty list of int
95 d: dict[str, int] = {} # Create empty dictionary (str -> int)
96
97
98 Compatibility of container types
99 ********************************
100
101 A quick note: container types can sometimes be unintuitive. We'll discuss this
102 more in :ref:`variance`. For example, the following program generates a mypy error,
103 because mypy treats ``list[int]`` as incompatible with ``list[object]``:
104
105 .. code-block:: python
106
107 def f(l: list[object], k: list[int]) -> None:
108 l = k # error: Incompatible types in assignment
109
110 The reason why the above assignment is disallowed is that allowing the
111 assignment could result in non-int values stored in a list of ``int``:
112
113 .. code-block:: python
114
115 def f(l: list[object], k: list[int]) -> None:
116 l = k
117 l.append('x')
118 print(k[-1]) # Ouch; a string in list[int]
119
120 Other container types like :py:class:`dict` and :py:class:`set` behave similarly.
121
122 You can still run the above program; it prints ``x``. This illustrates the fact
123 that static types do not affect the runtime behavior of programs. You can run
124 programs with type check failures, which is often very handy when performing a
125 large refactoring. Thus you can always 'work around' the type system, and it
126 doesn't really limit what you can do in your program.
127
128 Context in type inference
129 *************************
130
131 Type inference is *bidirectional* and takes context into account.
132
133 Mypy will take into account the type of the variable on the left-hand side
134 of an assignment when inferring the type of the expression on the right-hand
135 side. For example, the following will type check:
136
137 .. code-block:: python
138
139 def f(l: list[object]) -> None:
140 l = [1, 2] # Infer type list[object] for [1, 2], not list[int]
141
142
143 The value expression ``[1, 2]`` is type checked with the additional
144 context that it is being assigned to a variable of type ``list[object]``.
145 This is used to infer the type of the *expression* as ``list[object]``.
146
147 Declared argument types are also used for type context. In this program
148 mypy knows that the empty list ``[]`` should have type ``list[int]`` based
149 on the declared type of ``arg`` in ``foo``:
150
151 .. code-block:: python
152
153 def foo(arg: list[int]) -> None:
154 print('Items:', ', '.join(str(a) for a in arg))
155
156 foo([]) # OK
157
158 However, context only works within a single statement. Here mypy requires
159 an annotation for the empty list, since the context would only be available
160 in the following statement:
161
162 .. code-block:: python
163
164 def foo(arg: list[int]) -> None:
165 print('Items:', ', '.join(str(a) for a in arg))
166
167 a = [] # Error: Need type annotation for "a"
168 foo(a)
169
170 Working around the issue is easy by adding a type annotation:
171
172 .. code-block:: Python
173
174 ...
175 a: list[int] = [] # OK
176 foo(a)
177
178 .. _silencing-type-errors:
179
180 Silencing type errors
181 *********************
182
183 You might want to disable type checking on specific lines, or within specific
184 files in your codebase. To do that, you can use a ``# type: ignore`` comment.
185
186 For example, say in its latest update, the web framework you use can now take an
187 integer argument to ``run()``, which starts it on localhost on that port.
188 Like so:
189
190 .. code-block:: python
191
192 # Starting app on http://localhost:8000
193 app.run(8000)
194
195 However, the devs forgot to update their type annotations for
196 ``run``, so mypy still thinks ``run`` only expects ``str`` types.
197 This would give you the following error:
198
199 .. code-block:: text
200
201 error: Argument 1 to "run" of "A" has incompatible type "int"; expected "str"
202
203 If you cannot directly fix the web framework yourself, you can temporarily
204 disable type checking on that line, by adding a ``# type: ignore``:
205
206 .. code-block:: python
207
208 # Starting app on http://localhost:8000
209 app.run(8000) # type: ignore
210
211 This will suppress any mypy errors that would have raised on that specific line.
212
213 You should probably add some more information on the ``# type: ignore`` comment,
214 to explain why the ignore was added in the first place. This could be a link to
215 an issue on the repository responsible for the type stubs, or it could be a
216 short explanation of the bug. To do that, use this format:
217
218 .. code-block:: python
219
220 # Starting app on http://localhost:8000
221 app.run(8000) # type: ignore # `run()` in v2.0 accepts an `int`, as a port
222
223 Type ignore error codes
224 -----------------------
225
226 By default, mypy displays an error code for each error:
227
228 .. code-block:: text
229
230 error: "str" has no attribute "trim" [attr-defined]
231
232
233 It is possible to add a specific error-code in your ignore comment (e.g.
234 ``# type: ignore[attr-defined]``) to clarify what's being silenced. You can
235 find more information about error codes :ref:`here <silence-error-codes>`.
236
237 Other ways to silence errors
238 ----------------------------
239
240 You can get mypy to silence errors about a specific variable by dynamically
241 typing it with ``Any``. See :ref:`dynamic-typing` for more information.
242
243 .. code-block:: python
244
245 from typing import Any
246
247 def f(x: Any, y: str) -> None:
248 x = 'hello'
249 x += 1 # OK
250
251 You can ignore all mypy errors in a file by adding a
252 ``# mypy: ignore-errors`` at the top of the file:
253
254 .. code-block:: python
255
256 # mypy: ignore-errors
257 # This is a test file, skipping type checking in it.
258 import unittest
259 ...
260
261 You can also specify per-module configuration options in your :ref:`config-file`.
262 For example:
263
264 .. code-block:: ini
265
266 # Don't report errors in the 'package_to_fix_later' package
267 [mypy-package_to_fix_later.*]
268 ignore_errors = True
269
270 # Disable specific error codes in the 'tests' package
271 # Also don't require type annotations
272 [mypy-tests.*]
273 disable_error_code = var-annotated, has-type
274 allow_untyped_defs = True
275
276 # Silence import errors from the 'library_missing_types' package
277 [mypy-library_missing_types.*]
278 ignore_missing_imports = True
279
280 Finally, adding a ``@typing.no_type_check`` decorator to a class, method or
281 function causes mypy to avoid type checking that class, method or function
282 and to treat it as not having any type annotations.
283
284 .. code-block:: python
285
286 @typing.no_type_check
287 def foo() -> str:
288 return 12345 # No error!