Debian Codegraph @

docs/source/running_mypy.rst

raw
1 .. _running-mypy:
2
3 Running mypy and managing imports
4 =================================
5
6 The :ref:`getting-started` page should have already introduced you
7 to the basics of how to run mypy -- pass in the files and directories
8 you want to type check via the command line::
9
10 $ mypy foo.py bar.py some_directory
11
12 This page discusses in more detail how exactly to specify what files
13 you want mypy to type check, how mypy discovers imported modules,
14 and recommendations on how to handle any issues you may encounter
15 along the way.
16
17 If you are interested in learning about how to configure the
18 actual way mypy type checks your code, see our
19 :ref:`command-line` guide.
20
21
22 .. _specifying-code-to-be-checked:
23
24 Specifying code to be checked
25 *****************************
26
27 Mypy lets you specify what files it should type check in several different ways.
28
29 1. First, you can pass in paths to Python files and directories you
30 want to type check. For example::
31
32 $ mypy file_1.py foo/file_2.py file_3.pyi some/directory
33
34 The above command tells mypy it should type check all of the provided
35 files together. In addition, mypy will recursively type check the
36 entire contents of any provided directories.
37
38 For more details about how exactly this is done, see
39 :ref:`Mapping file paths to modules <mapping-paths-to-modules>`.
40
41 2. Second, you can use the :option:`-m <mypy -m>` flag (long form: :option:`--module <mypy --module>`) to
42 specify a module name to be type checked. The name of a module
43 is identical to the name you would use to import that module
44 within a Python program. For example, running::
45
46 $ mypy -m html.parser
47
48 ...will type check the module ``html.parser`` (this happens to be
49 a library stub).
50
51 Mypy will use an algorithm very similar to the one Python uses to
52 find where modules and imports are located on the file system.
53 For more details, see :ref:`finding-imports`.
54
55 3. Third, you can use the :option:`-p <mypy -p>` (long form: :option:`--package <mypy --package>`) flag to
56 specify a package to be (recursively) type checked. This flag
57 is almost identical to the :option:`-m <mypy -m>` flag except that if you give it
58 a package name, mypy will recursively type check all submodules
59 and subpackages of that package. For example, running::
60
61 $ mypy -p html
62
63 ...will type check the entire ``html`` package (of library stubs).
64 In contrast, if we had used the :option:`-m <mypy -m>` flag, mypy would have type
65 checked just ``html``'s ``__init__.py`` file and anything imported
66 from there.
67
68 Note that we can specify multiple packages and modules on the
69 command line. For example::
70
71 $ mypy --package p.a --package p.b --module c
72
73 4. Fourth, you can also instruct mypy to directly type check small
74 strings as programs by using the :option:`-c <mypy -c>` (long form: :option:`--command <mypy --command>`)
75 flag. For example::
76
77 $ mypy -c 'x = [1, 2]; print(x())'
78
79 ...will type check the above string as a mini-program (and in this case,
80 will report that ``list[int]`` is not callable).
81
82 You can also use the :confval:`files` option in your :file:`mypy.ini` file to specify which
83 files to check, in which case you can simply run ``mypy`` with no arguments.
84
85
86 Reading a list of files from a file
87 ***********************************
88
89 Finally, any command-line argument starting with ``@`` reads additional
90 command-line arguments from the file following the ``@`` character.
91 This is primarily useful if you have a file containing a list of files
92 that you want to be type-checked: instead of using shell syntax like::
93
94 $ mypy $(cat file_of_files.txt)
95
96 you can use this instead::
97
98 $ mypy @file_of_files.txt
99
100 This file can technically also contain any command line flag, not
101 just file paths. However, if you want to configure many different
102 flags, the recommended approach is to use a
103 :ref:`configuration file <config-file>` instead.
104
105
106 .. _mapping-paths-to-modules:
107
108 Mapping file paths to modules
109 *****************************
110
111 One of the main ways you can tell mypy what to type check
112 is by providing mypy a list of paths. For example::
113
114 $ mypy file_1.py foo/file_2.py file_3.pyi some/directory
115
116 This section describes how exactly mypy maps the provided paths
117 to modules to type check.
118
119 - Mypy will check all paths provided that correspond to files.
120
121 - Mypy will recursively discover and check all files ending in ``.py`` or
122 ``.pyi`` in directory paths provided, after accounting for
123 :option:`--exclude <mypy --exclude>`.
124
125 - For each file to be checked, mypy will attempt to associate the file (e.g.
126 ``project/foo/bar/baz.py``) with a fully qualified module name (e.g.
127 ``foo.bar.baz``). The directory the package is in (``project``) is then
128 added to mypy's module search paths.
129
130 How mypy determines fully qualified module names depends on if the options
131 :option:`--no-namespace-packages <mypy --no-namespace-packages>` and
132 :option:`--explicit-package-bases <mypy --explicit-package-bases>` are set.
133
134 1. If :option:`--no-namespace-packages <mypy --no-namespace-packages>` is set,
135 mypy will rely solely upon the presence of ``__init__.py[i]`` files to
136 determine the fully qualified module name. That is, mypy will crawl up the
137 directory tree for as long as it continues to find ``__init__.py`` (or
138 ``__init__.pyi``) files.
139
140 For example, if your directory tree consists of ``pkg/subpkg/mod.py``, mypy
141 would require ``pkg/__init__.py`` and ``pkg/subpkg/__init__.py`` to exist in
142 order correctly associate ``mod.py`` with ``pkg.subpkg.mod``
143
144 2. The default case. If :option:`--namespace-packages <mypy
145 --no-namespace-packages>` is on, but :option:`--explicit-package-bases <mypy
146 --explicit-package-bases>` is off, mypy will allow for the possibility that
147 directories without ``__init__.py[i]`` are packages. Specifically, mypy will
148 look at all parent directories of the file and use the location of the
149 highest ``__init__.py[i]`` in the directory tree to determine the top-level
150 package.
151
152 For example, say your directory tree consists solely of ``pkg/__init__.py``
153 and ``pkg/a/b/c/d/mod.py``. When determining ``mod.py``'s fully qualified
154 module name, mypy will look at ``pkg/__init__.py`` and conclude that the
155 associated module name is ``pkg.a.b.c.d.mod``.
156
157 3. You'll notice that the above case still relies on ``__init__.py``. If
158 you can't put an ``__init__.py`` in your top-level package, but still wish to
159 pass paths (as opposed to packages or modules using the ``-p`` or ``-m``
160 flags), :option:`--explicit-package-bases <mypy --explicit-package-bases>`
161 provides a solution.
162
163 With :option:`--explicit-package-bases <mypy --explicit-package-bases>`, mypy
164 will locate the nearest parent directory that is a member of the ``MYPYPATH``
165 environment variable, the :confval:`mypy_path` config or is the current
166 working directory. Mypy will then use the relative path to determine the
167 fully qualified module name.
168
169 For example, say your directory tree consists solely of
170 ``src/namespace_pkg/mod.py``. If you run the following command, mypy
171 will correctly associate ``mod.py`` with ``namespace_pkg.mod``::
172
173 $ MYPYPATH=src mypy --namespace-packages --explicit-package-bases .
174
175 If you pass a file not ending in ``.py[i]``, the module name assumed is
176 ``__main__`` (matching the behavior of the Python interpreter), unless
177 :option:`--scripts-are-modules <mypy --scripts-are-modules>` is passed.
178
179 Passing :option:`-v <mypy -v>` will show you the files and associated module
180 names that mypy will check.
181
182
183 How mypy handles imports
184 ************************
185
186 When mypy encounters an ``import`` statement, it will first
187 :ref:`attempt to locate <finding-imports>` that module
188 or type stubs for that module in the file system. Mypy will then
189 type check the imported module. There are three different outcomes
190 of this process:
191
192 1. Mypy is unable to follow the import: the module either does not
193 exist, or is a third party library that does not use type hints.
194
195 2. Mypy is able to follow and type check the import, but you did
196 not want mypy to type check that module at all.
197
198 3. Mypy is able to successfully both follow and type check the
199 module, and you want mypy to type check that module.
200
201 The third outcome is what mypy will do in the ideal case. The following
202 sections will discuss what to do in the other two cases.
203
204 .. _ignore-missing-imports:
205 .. _fix-missing-imports:
206
207 Missing imports
208 ***************
209
210 When you import a module, mypy may report that it is unable to follow
211 the import. This can cause errors that look like the following:
212
213 .. code-block:: text
214
215 main.py:1: error: Skipping analyzing 'django': module is installed, but missing library stubs or py.typed marker
216 main.py:2: error: Library stubs not installed for "requests"
217 main.py:3: error: Cannot find implementation or library stub for module named "this_module_does_not_exist"
218
219 If you get any of these errors on an import, mypy will assume the type of that
220 module is ``Any``, the dynamic type. This means attempting to access any
221 attribute of the module will automatically succeed:
222
223 .. code-block:: python
224
225 # Error: Cannot find implementation or library stub for module named 'does_not_exist'
226 import does_not_exist
227
228 # But this type checks, and x will have type 'Any'
229 x = does_not_exist.foobar()
230
231 This can result in mypy failing to warn you about errors in your code. Since
232 operations on ``Any`` result in ``Any``, these dynamic types can propagate
233 through your code, making type checking less effective. See
234 :ref:`dynamic-typing` for more information.
235
236 The next sections describe what each of these errors means and recommended next steps; scroll to
237 the section that matches your error.
238
239
240 Missing library stubs or py.typed marker
241 ----------------------------------------
242
243 If you are getting a ``Skipping analyzing X: module is installed, but missing library stubs or py.typed marker``,
244 error, this means mypy was able to find the module you were importing, but no
245 corresponding type hints.
246
247 Mypy will not try inferring the types of any 3rd party libraries you have installed
248 unless they either have declared themselves to be
249 :ref:`PEP 561 compliant stub package <installed-packages>` (e.g. with a ``py.typed`` file) or have registered
250 themselves on `typeshed <https://github.com/python/typeshed>`_, the repository
251 of types for the standard library and some 3rd party libraries.
252
253 If you are getting this error, try to obtain type hints for the library you're using:
254
255 1. Upgrading the version of the library you're using, in case a newer version
256 has started to include type hints.
257
258 2. Searching to see if there is a :ref:`PEP 561 compliant stub package <installed-packages>`
259 corresponding to your third party library. Stub packages let you install
260 type hints independently from the library itself.
261
262 For example, if you want type hints for the ``django`` library, you can
263 install the `django-stubs <https://pypi.org/project/django-stubs/>`_ package.
264
265 3. :ref:`Writing your own stub files <stub-files>` containing type hints for
266 the library. You can point mypy at your type hints either by passing
267 them in via the command line, by using the :confval:`files` or :confval:`mypy_path`
268 config file options, or by
269 adding the location to the ``MYPYPATH`` environment variable.
270
271 These stub files do not need to be complete! A good strategy is to use
272 :ref:`stubgen <stubgen>`, a program that comes bundled with mypy, to generate a first
273 rough draft of the stubs. You can then iterate on just the parts of the
274 library you need.
275
276 If you want to share your work, you can try contributing your stubs back
277 to the library -- see our documentation on creating
278 :ref:`PEP 561 compliant packages <installed-packages>`.
279
280 4. Force mypy to analyze the library as best as it can (as if the library provided
281 a ``py.typed`` file), despite it likely missing any type annotations. In general,
282 the quality of type checking will be poor and mypy may have issues when
283 analyzing code not designed to be type checked.
284
285 You can do this via setting the
286 :option:`--follow-untyped-imports <mypy --follow-untyped-imports>`
287 command line flag or :confval:`follow_untyped_imports` config file option to True.
288 This option can be specified on a per-module basis as well:
289
290 .. tab:: mypy.ini
291
292 .. code-block:: ini
293
294 [mypy-untyped_package.*]
295 follow_untyped_imports = True
296
297 .. tab:: pyproject.toml
298
299 .. code-block:: toml
300
301 [[tool.mypy.overrides]]
302 module = ["untyped_package.*"]
303 follow_untyped_imports = true
304
305 If you are unable to find any existing type hints nor have time to write your
306 own, you can instead *suppress* the errors.
307
308 All this will do is make mypy stop reporting an error on the line containing the
309 import: the imported module will continue to be of type ``Any``, and mypy may
310 not catch errors in its use.
311
312 1. To suppress a *single* missing import error, add a ``# type: ignore`` at the end of the
313 line containing the import.
314
315 2. To suppress *all* missing import errors from a single library, add
316 a per-module section to your :ref:`mypy config file <config-file>` setting
317 :confval:`ignore_missing_imports` to True for that library. For example,
318 suppose your codebase
319 makes heavy use of an (untyped) library named ``foobar``. You can silence
320 all import errors associated with that library and that library alone by
321 adding the following section to your config file:
322
323 .. tab:: mypy.ini
324
325 .. code-block:: ini
326
327 [mypy-foobar.*]
328 ignore_missing_imports = True
329
330 .. tab:: pyproject.toml
331
332 .. code-block:: toml
333
334 [[tool.mypy.overrides]]
335 module = ["foobar.*"]
336 ignore_missing_imports = true
337
338 Note: this option is equivalent to adding a ``# type: ignore`` to every
339 import of ``foobar`` in your codebase. For more information, see the
340 documentation about configuring
341 :ref:`import discovery <config-file-import-discovery>` in config files.
342 The ``.*`` after ``foobar`` will ignore imports of ``foobar`` modules
343 and subpackages in addition to the ``foobar`` top-level package namespace.
344
345 3. To suppress *all* missing import errors for *all* untyped libraries
346 in your codebase, use :option:`--disable-error-code=import-untyped <mypy --ignore-missing-imports>`.
347 See :ref:`code-import-untyped` for more details on this error code.
348
349 You can also set :confval:`disable_error_code`, like so:
350
351 .. tab:: mypy.ini
352
353 .. code-block:: ini
354
355 [mypy]
356 disable_error_code = import-untyped
357
358 .. tab:: pyproject.toml
359
360 .. code-block:: ini
361
362 [tool.mypy]
363 disable_error_code = ["import-untyped"]
364
365 You can also set the :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`
366 command line flag or set the :confval:`ignore_missing_imports` config file
367 option to True in the *global* section of your mypy config file. We
368 recommend avoiding ``--ignore-missing-imports`` if possible: it's equivalent
369 to adding a ``# type: ignore`` to all unresolved imports in your codebase.
370
371
372 Library stubs not installed
373 ---------------------------
374
375 If mypy can't find stubs for a third-party library, and it knows that stubs exist for
376 the library, you will get a message like this:
377
378 .. code-block:: text
379
380 main.py:1: error: Library stubs not installed for "yaml"
381 main.py:1: note: Hint: "python3 -m pip install types-PyYAML"
382 main.py:1: note: (or run "mypy --install-types" to install all missing stub packages)
383
384 You can resolve the issue by running the suggested pip commands.
385 If you're running mypy in CI, you can ensure the presence of any stub packages
386 you need the same as you would any other test dependency, e.g. by adding them to
387 the appropriate ``requirements.txt`` file.
388
389 Alternatively, add the :option:`--install-types <mypy --install-types>`
390 to your mypy command to install all known missing stubs:
391
392 .. code-block:: text
393
394 mypy --install-types
395
396 This is slower than explicitly installing stubs, since it effectively
397 runs mypy twice -- the first time to find the missing stubs, and
398 the second time to type check your code properly after mypy has
399 installed the stubs. It also can make controlling stub versions harder,
400 resulting in less reproducible type checking.
401
402 By default, :option:`--install-types <mypy --install-types>` shows a confirmation prompt.
403 Use :option:`--non-interactive <mypy --non-interactive>` to install all suggested
404 stub packages without asking for confirmation *and* type check your code:
405
406 If you've already installed the relevant third-party libraries in an environment
407 other than the one mypy is running in, you can use :option:`--python-executable
408 <mypy --python-executable>` flag to point to the Python executable for that
409 environment, and mypy will find packages installed for that Python executable.
410
411 If you've installed the relevant stub packages and are still getting this error,
412 see the :ref:`section below <missing-type-hints-for-third-party-library>`.
413
414 .. _missing-type-hints-for-third-party-library:
415
416 Cannot find implementation or library stub
417 ------------------------------------------
418
419 If you are getting a ``Cannot find implementation or library stub for module``
420 error, this means mypy was not able to find the module you are trying to
421 import, whether it comes bundled with type hints or not. If you are getting
422 this error, try:
423
424 1. Making sure your import does not contain a typo.
425
426 2. If the module is a third party library, making sure that mypy is able
427 to find the interpreter containing the installed library.
428
429 For example, if you are running your code in a virtualenv, make sure
430 to install and use mypy within the virtualenv. Alternatively, if you
431 want to use a globally installed mypy, set the
432 :option:`--python-executable <mypy --python-executable>` command
433 line flag to point the Python interpreter containing your installed
434 third party packages.
435
436 You can confirm that you are running mypy from the environment you expect
437 by running it like ``python -m mypy ...``. You can confirm that you are
438 installing into the environment you expect by running pip like
439 ``python -m pip ...``.
440
441 3. Reading the :ref:`finding-imports` section below to make sure you
442 understand how exactly mypy searches for and finds modules and modify
443 how you're invoking mypy accordingly.
444
445 4. Directly specifying the directory containing the module you want to
446 type check from the command line, by using the :confval:`mypy_path`
447 or :confval:`files` config file options,
448 or by using the ``MYPYPATH`` environment variable.
449
450 Note: if the module you are trying to import is actually a *submodule* of
451 some package, you should specify the directory containing the *entire* package.
452 For example, suppose you are trying to add the module ``foo.bar.baz``
453 which is located at ``~/foo-project/src/foo/bar/baz.py``. In this case,
454 you must run ``mypy ~/foo-project/src`` (or set the ``MYPYPATH`` to
455 ``~/foo-project/src``).
456
457 .. _finding-imports:
458
459 How imports are found
460 *********************
461
462 When mypy encounters an ``import`` statement or receives module
463 names from the command line via the :option:`--module <mypy --module>` or :option:`--package <mypy --package>`
464 flags, mypy tries to find the module on the file system similar
465 to the way Python finds it. However, there are some differences.
466
467 First, mypy has its own search path.
468 This is computed from the following items:
469
470 - The ``MYPYPATH`` environment variable
471 (a list of directories, colon-separated on UNIX systems, semicolon-separated on Windows).
472 - The :confval:`mypy_path` config file option.
473 - The directories containing the sources given on the command line
474 (see :ref:`Mapping file paths to modules <mapping-paths-to-modules>`).
475 - The installed packages marked as safe for type checking (see
476 :ref:`PEP 561 support <installed-packages>`)
477 - The relevant directories of the
478 `typeshed <https://github.com/python/typeshed>`_ repo.
479
480 .. note::
481
482 You cannot point to a stub-only package (:pep:`561`) via the ``MYPYPATH``, it must be
483 installed (see :ref:`PEP 561 support <installed-packages>`)
484
485 Second, mypy searches for stub files in addition to regular Python files
486 and packages.
487 The rules for searching for a module ``foo`` are as follows:
488
489 - The search looks in each of the directories in the search path
490 (see above) until a match is found.
491 - If a package named ``foo`` is found (i.e. a directory
492 ``foo`` containing an ``__init__.py`` or ``__init__.pyi`` file)
493 that's a match.
494 - If a stub file named ``foo.pyi`` is found, that's a match.
495 - If a Python module named ``foo.py`` is found, that's a match.
496
497 These matches are tried in order, so that if multiple matches are found
498 in the same directory on the search path
499 (e.g. a package and a Python file, or a stub file and a Python file)
500 the first one in the above list wins.
501
502 In particular, if a Python file and a stub file are both present in the
503 same directory on the search path, only the stub file is used.
504 (However, if the files are in different directories, the one found
505 in the earlier directory is used.)
506
507 Setting :confval:`mypy_path`/``MYPYPATH`` is mostly useful in the case
508 where you want to try running mypy against multiple distinct
509 sets of files that happen to share some common dependencies.
510
511 For example, if you have multiple projects that happen to be
512 using the same set of work-in-progress stubs, it could be
513 convenient to just have your ``MYPYPATH`` point to a single
514 directory containing the stubs.
515
516 .. _follow-imports:
517
518 Following imports
519 *****************
520
521 Mypy is designed to :ref:`doggedly follow all imports <finding-imports>`,
522 even if the imported module is not a file you explicitly wanted mypy to check.
523
524 For example, suppose we have two modules ``mycode.foo`` and ``mycode.bar``:
525 the former has type hints and the latter does not. We run
526 :option:`mypy -m mycode.foo <mypy -m>` and mypy discovers that ``mycode.foo`` imports
527 ``mycode.bar``.
528
529 How do we want mypy to type check ``mycode.bar``? Mypy's behaviour here is
530 configurable -- although we **strongly recommend** using the default --
531 by using the :option:`--follow-imports <mypy --follow-imports>` flag. This flag
532 accepts one of four string values:
533
534 - ``normal`` (the default, recommended) follows all imports normally and
535 type checks all top level code (as well as the bodies of all
536 functions and methods with at least one type annotation in
537 the signature).
538
539 - ``silent`` behaves in the same way as ``normal`` but will
540 additionally *suppress* any error messages.
541
542 - ``skip`` will *not* follow imports and instead will silently
543 replace the module (and *anything imported from it*) with an
544 object of type ``Any``.
545
546 - ``error`` behaves in the same way as ``skip`` but is not quite as
547 silent -- it will flag the import as an error, like this::
548
549 main.py:1: note: Import of "mycode.bar" ignored
550 main.py:1: note: (Using --follow-imports=error, module not passed on command line)
551
552 If you are starting a new codebase and plan on using type hints from
553 the start, we **recommend** you use either :option:`--follow-imports=normal <mypy --follow-imports>`
554 (the default) or :option:`--follow-imports=error <mypy --follow-imports>`. Either option will help
555 make sure you are not skipping checking any part of your codebase by
556 accident.
557
558 If you are planning on adding type hints to a large, existing code base,
559 we recommend you start by trying to make your entire codebase (including
560 files that do not use type hints) pass under :option:`--follow-imports=normal <mypy --follow-imports>`.
561 This is usually not too difficult to do: mypy is designed to report as
562 few error messages as possible when it is looking at unannotated code.
563
564 Only if doing this is intractable, try passing mypy just the files
565 you want to type check and using :option:`--follow-imports=silent <mypy --follow-imports>`.
566 Even if mypy is unable to perfectly type check a file, it can still glean some
567 useful information by parsing it (for example, understanding what methods
568 a given object has). See :ref:`existing-code` for more recommendations.
569
570 Adjusting import following behaviour is often most useful when restricted to
571 specific modules. This can be accomplished by setting a per-module
572 :confval:`follow_imports` config option.
573
574 .. warning::
575
576 We do not recommend using ``follow_imports=skip`` unless you're really sure
577 you know what you are doing. This option greatly restricts the analysis mypy
578 can perform and you will lose a lot of the benefits of type checking.
579
580 This is especially true at the global level. Setting a per-module
581 ``follow_imports=skip`` for a specific problematic module can be
582 useful without causing too much harm.
583
584 .. note::
585
586 If you're looking to resolve import errors related to libraries, try following
587 the advice in :ref:`fix-missing-imports` before messing with ``follow_imports``.