Debian Codegraph @

docs/source/config_file.rst

raw
1 .. _config-file:
2
3 The mypy configuration file
4 ===========================
5
6 Mypy is very configurable. This is most useful when introducing typing to
7 an existing codebase. See :ref:`existing-code` for concrete advice for
8 that situation.
9
10 Mypy supports reading configuration settings from a file. By default, mypy will
11 discover configuration files by walking up the file system (up until the root of
12 a repository or the root of the filesystem). In each directory, it will look for
13 the following configuration files (in this order):
14
15 1. ``mypy.ini``
16 2. ``.mypy.ini``
17 3. ``pyproject.toml`` (containing a ``[tool.mypy]`` section)
18 4. ``setup.cfg`` (containing a ``[mypy]`` section)
19
20 If no configuration file is found by this method, mypy will then look for
21 configuration files in the following locations (in this order):
22
23 1. ``$XDG_CONFIG_HOME/mypy/config``
24 2. ``~/.config/mypy/config``
25 3. ``~/.mypy.ini``
26
27 The :option:`--config-file <mypy --config-file>` command-line flag has the
28 highest precedence and must point towards a valid configuration file;
29 otherwise mypy will report an error and exit. Without the command line option,
30 mypy will look for configuration files in the precedence order above.
31
32 It is important to understand that there is no merging of configuration
33 files, as it would lead to ambiguity.
34
35 Most flags correspond closely to :ref:`command-line flags
36 <command-line>` but there are some differences in flag names and some
37 flags may take a different value based on the module being processed.
38
39 Some flags support user home directory and environment variable expansion.
40 To refer to the user home directory, use ``~`` at the beginning of the path.
41 To expand environment variables use ``$VARNAME`` or ``${VARNAME}``.
42
43
44 Config file format
45 ******************
46
47 The configuration file format is the usual
48 :doc:`ini file <python:library/configparser>` format. It should contain
49 section names in square brackets and flag settings of the form
50 `NAME = VALUE`. Comments start with ``#`` characters.
51
52 - A section named ``[mypy]`` must be present. This specifies
53 the global flags.
54
55 - Additional sections named ``[mypy-PATTERN1,PATTERN2,...]`` may be
56 present, where ``PATTERN1``, ``PATTERN2``, etc., are comma-separated
57 patterns of fully-qualified module names, with some components optionally
58 replaced by the '*' character (e.g. ``foo.bar``, ``foo.bar.*``, ``foo.*.baz``).
59 These sections specify additional flags that only apply to *modules*
60 whose name matches at least one of the patterns.
61
62 A pattern of the form ``qualified_module_name`` matches only the named module,
63 while ``dotted_module_name.*`` matches ``dotted_module_name`` and any
64 submodules (so ``foo.bar.*`` would match all of ``foo.bar``,
65 ``foo.bar.baz``, and ``foo.bar.baz.quux``).
66
67 Patterns may also be "unstructured" wildcards, in which stars may
68 appear in the middle of a name (e.g
69 ``site.*.migrations.*``). Stars match zero or more module
70 components (so ``site.*.migrations.*`` can match ``site.migrations``).
71
72 .. _config-precedence:
73
74 When options conflict, the precedence order for configuration is:
75
76 1. :ref:`Inline configuration <inline-config>` in the source file
77 2. Sections with concrete module names (``foo.bar``)
78 3. Sections with "unstructured" wildcard patterns (``foo.*.baz``),
79 with sections later in the configuration file overriding
80 sections earlier.
81 4. Sections with "well-structured" wildcard patterns
82 (``foo.bar.*``), with more specific overriding more general.
83 5. Command line options.
84 6. Top-level configuration file options.
85
86 The difference in precedence order between "structured" patterns (by
87 specificity) and "unstructured" patterns (by order in the file) is
88 unfortunate, and is subject to change in future versions.
89
90 .. note::
91
92 The :confval:`warn_unused_configs` flag may be useful to debug misspelled
93 section names.
94
95 .. note::
96
97 Configuration flags are liable to change between releases.
98
99
100 Per-module and global options
101 *****************************
102
103 Some of the config options may be set either globally (in the ``[mypy]`` section)
104 or on a per-module basis (in sections like ``[mypy-foo.bar]``).
105
106 If you set an option both globally and for a specific module, the module configuration
107 options take precedence. This lets you set global defaults and override them on a
108 module-by-module basis. If multiple pattern sections match a module, :ref:`the options from the
109 most specific section are used where they disagree <config-precedence>`.
110
111 Some other options, as specified in their description,
112 may only be set in the global section (``[mypy]``).
113
114
115 Inverting option values
116 ***********************
117
118 Options that take a boolean value may be inverted by adding ``no_`` to
119 their name or by (when applicable) swapping their prefix from
120 ``disallow`` to ``allow`` (and vice versa).
121
122
123 Example ``mypy.ini``
124 ********************
125
126 Here is an example of a ``mypy.ini`` file. To use this config file, place it at the root
127 of your repo and run mypy.
128
129 .. code-block:: ini
130
131 # Global options:
132
133 [mypy]
134 warn_return_any = True
135 warn_unused_configs = True
136
137 # Per-module options:
138
139 [mypy-mycode.foo.*]
140 disallow_untyped_defs = True
141
142 [mypy-mycode.bar]
143 warn_return_any = False
144
145 [mypy-somelibrary]
146 ignore_missing_imports = True
147
148 This config file specifies two global options in the ``[mypy]`` section. These two
149 options will:
150
151 1. Report an error whenever a function returns a value that is inferred
152 to have type ``Any``.
153
154 2. Report any config options that are unused by mypy. (This will help us catch typos
155 when making changes to our config file).
156
157 Next, this module specifies three per-module options. The first two options change how mypy
158 type checks code in ``mycode.foo.*`` and ``mycode.bar``, which we assume here are two modules
159 that you wrote. The final config option changes how mypy type checks ``somelibrary``, which we
160 assume here is some 3rd party library you've installed and are importing. These options will:
161
162 1. Selectively disallow untyped function definitions only within the ``mycode.foo``
163 package -- that is, only for function definitions defined in the
164 ``mycode/foo`` directory.
165
166 2. Selectively *disable* the "function is returning any" warnings within
167 ``mycode.bar`` only. This overrides the global default we set earlier.
168
169 3. Suppress any error messages generated when your codebase tries importing the
170 module ``somelibrary``. This is useful if ``somelibrary`` is some 3rd party library
171 missing type hints.
172
173
174 .. _config-file-import-discovery:
175
176 Import discovery
177 ****************
178
179 For more information, see the :ref:`Import discovery <import-discovery>`
180 section of the command line docs.
181
182 .. confval:: mypy_path
183
184 :type: string
185
186 Specifies the paths to use, after trying the paths from ``MYPYPATH`` environment
187 variable. Useful if you'd like to keep stubs in your repo, along with the config file.
188 Multiple paths are always separated with a ``:`` or ``,`` regardless of the platform.
189 User home directory and environment variables will be expanded.
190
191 Relative paths are treated relative to the working directory of the mypy command,
192 not the config file.
193 Use the ``MYPY_CONFIG_FILE_DIR`` environment variable to refer to paths relative to
194 the config file (e.g. ``mypy_path = $MYPY_CONFIG_FILE_DIR/src``).
195
196 This option may only be set in the global section (``[mypy]``).
197
198 **Note:** On Windows, use UNC paths to avoid using ``:`` (e.g. ``\\127.0.0.1\X$\MyDir`` where ``X`` is the drive letter).
199
200 .. confval:: files
201
202 :type: comma-separated list of strings
203
204 A comma-separated list of paths which should be checked by mypy if none are given on the command
205 line. Supports recursive file globbing using :py:mod:`glob`, where ``*`` (e.g. ``*.py``) matches
206 files in the current directory and ``**/`` (e.g. ``**/*.py``) matches files in any directories below
207 the current one. User home directory and environment variables will be expanded.
208
209 This option may only be set in the global section (``[mypy]``).
210
211 .. confval:: modules
212
213 :type: comma-separated list of strings
214
215 A comma-separated list of packages which should be checked by mypy if none are given on the command
216 line. Mypy *will not* recursively type check any submodules of the provided
217 module.
218
219 This option may only be set in the global section (``[mypy]``).
220
221
222 .. confval:: packages
223
224 :type: comma-separated list of strings
225
226 A comma-separated list of packages which should be checked by mypy if none are given on the command
227 line. Mypy *will* recursively type check any submodules of the provided
228 package. This flag is identical to :confval:`modules` apart from this
229 behavior.
230
231 This option may only be set in the global section (``[mypy]``).
232
233 .. confval:: exclude
234
235 :type: regular expression
236
237 A regular expression that matches file names, directory names and paths
238 which mypy should ignore while recursively discovering files to check.
239 Use forward slashes (``/``) as directory separators on all platforms.
240
241 .. code-block:: ini
242
243 [mypy]
244 exclude = (?x)(
245 ^one\.py$ # files named "one.py"
246 | two\.pyi$ # or files ending with "two.pyi"
247 | ^three\. # or files starting with "three."
248 )
249
250 Crafting a single regular expression that excludes multiple files while remaining
251 human-readable can be a challenge. The above example demonstrates one approach.
252 ``(?x)`` enables the ``VERBOSE`` flag for the subsequent regular expression, which
253 :py:data:`ignores most whitespace and supports comments <re.VERBOSE>`.
254 The above is equivalent to: ``(^one\.py$|two\.pyi$|^three\.)``.
255
256 For more details, see :option:`--exclude <mypy --exclude>`.
257
258 This option may only be set in the global section (``[mypy]``).
259
260 .. note::
261
262 Note that the TOML equivalent differs slightly. It can be either a single string
263 (including a multi-line string) -- which is treated as a single regular
264 expression -- or an array of such strings. The following TOML examples are
265 equivalent to the above INI example.
266
267 Array of strings:
268
269 .. code-block:: toml
270
271 [tool.mypy]
272 exclude = [
273 "^one\\.py$", # TOML's double-quoted strings require escaping backslashes
274 'two\.pyi$', # but TOML's single-quoted strings do not
275 '^three\.',
276 ]
277
278 A single, multi-line string:
279
280 .. code-block:: toml
281
282 [tool.mypy]
283 exclude = '''(?x)(
284 ^one\.py$ # files named "one.py"
285 | two\.pyi$ # or files ending with "two.pyi"
286 | ^three\. # or files starting with "three."
287 )''' # TOML's single-quoted strings do not require escaping backslashes
288
289 See :ref:`using-a-pyproject-toml`.
290
291 .. confval:: exclude_gitignore
292
293 :type: boolean
294 :default: False
295
296 This flag will add everything that matches ``.gitignore`` file(s) to :confval:`exclude`.
297 This option may only be set in the global section (``[mypy]``).
298
299 .. confval:: namespace_packages
300
301 :type: boolean
302 :default: True
303
304 Enables :pep:`420` style namespace packages. See the
305 corresponding flag :option:`--no-namespace-packages <mypy --no-namespace-packages>`
306 for more information.
307
308 This option may only be set in the global section (``[mypy]``).
309
310 .. confval:: explicit_package_bases
311
312 :type: boolean
313 :default: False
314
315 This flag tells mypy that top-level packages will be based in either the
316 current directory, or a member of the ``MYPYPATH`` environment variable or
317 :confval:`mypy_path` config option. This option is only useful in
318 the absence of `__init__.py`. See :ref:`Mapping file
319 paths to modules <mapping-paths-to-modules>` for details.
320
321 This option may only be set in the global section (``[mypy]``).
322
323 .. confval:: ignore_missing_imports
324
325 :type: boolean
326 :default: False
327
328 Suppresses error messages about imports that cannot be resolved.
329
330 If this option is used in a per-module section, the module name should
331 match the name of the *imported* module, not the module containing the
332 import statement.
333
334 .. confval:: follow_untyped_imports
335
336 :type: boolean
337 :default: False
338
339 Makes mypy analyze imports from installed packages even if missing a
340 :ref:`py.typed marker or stubs <installed-packages>`.
341
342 If this option is used in a per-module section, the module name should
343 match the name of the *imported* module, not the module containing the
344 import statement.
345
346 .. warning::
347
348 Note that analyzing all unannotated modules might result in issues
349 when analyzing code not designed to be type checked and may significantly
350 increase how long mypy takes to run.
351
352 .. confval:: follow_imports
353
354 :type: string
355 :default: ``normal``
356
357 Directs what to do with imports when the imported module is found
358 as a ``.py`` file and not part of the files, modules and packages
359 provided on the command line.
360
361 The four possible values are ``normal``, ``silent``, ``skip`` and
362 ``error``. For explanations see the discussion for the
363 :option:`--follow-imports <mypy --follow-imports>` command line flag.
364
365 Using this option in a per-module section (potentially with a wildcard,
366 as described at the top of this page) is a good way to prevent mypy from
367 checking portions of your code.
368
369 If this option is used in a per-module section, the module name should
370 match the name of the *imported* module, not the module containing the
371 import statement.
372
373 .. confval:: follow_imports_for_stubs
374
375 :type: boolean
376 :default: False
377
378 Determines whether to respect the :confval:`follow_imports` setting even for
379 stub (``.pyi``) files.
380
381 Used in conjunction with :confval:`follow_imports=skip <follow_imports>`, this can be used
382 to suppress the import of a module from ``typeshed``, replacing it
383 with ``Any``.
384
385 Used in conjunction with :confval:`follow_imports=error <follow_imports>`, this can be used
386 to make any use of a particular ``typeshed`` module an error.
387
388 .. note::
389
390 This is not supported by the mypy daemon.
391
392 .. confval:: python_executable
393
394 :type: string
395
396 Specifies the path to the Python executable to inspect to collect
397 a list of available :ref:`PEP 561 packages <installed-packages>`. User
398 home directory and environment variables will be expanded. Defaults to
399 the executable used to run mypy.
400
401 This option may only be set in the global section (``[mypy]``).
402
403 .. confval:: no_site_packages
404
405 :type: boolean
406 :default: False
407
408 Disables using type information in installed packages (see :pep:`561`).
409 This will also disable searching for a usable Python executable. This acts
410 the same as :option:`--no-site-packages <mypy --no-site-packages>` command
411 line flag.
412
413 .. confval:: no_silence_site_packages
414
415 :type: boolean
416 :default: False
417
418 Enables reporting error messages generated within installed packages (see
419 :pep:`561` for more details on distributing type information). Those error
420 messages are suppressed by default, since you are usually not able to
421 control errors in 3rd party code.
422
423 This option may only be set in the global section (``[mypy]``).
424
425
426 Platform configuration
427 **********************
428
429 .. confval:: python_version
430
431 :type: string
432
433 Specifies the Python version used to parse and check the target
434 program. The string should be in the format ``MAJOR.MINOR`` --
435 for example ``3.10``. The default is the version of the Python
436 interpreter used to run mypy.
437
438 This option may only be set in the global section (``[mypy]``).
439
440 .. confval:: platform
441
442 :type: string
443
444 Specifies the OS platform for the target program, for example
445 ``darwin`` or ``win32`` (meaning OS X or Windows, respectively).
446 The default is the current platform as revealed by Python's
447 :py:data:`sys.platform` variable.
448
449 This option may only be set in the global section (``[mypy]``).
450
451 .. confval:: always_true
452
453 :type: comma-separated list of strings
454
455 Specifies a list of variables that mypy will treat as
456 compile-time constants that are always true.
457
458 .. confval:: always_false
459
460 :type: comma-separated list of strings
461
462 Specifies a list of variables that mypy will treat as
463 compile-time constants that are always false.
464
465
466 Disallow dynamic typing
467 ***********************
468
469 For more information, see the :ref:`Disallow dynamic typing <disallow-dynamic-typing>`
470 section of the command line docs.
471
472 .. confval:: disallow_any_unimported
473
474 :type: boolean
475 :default: False
476
477 Disallows usage of types that come from unfollowed imports (anything imported from
478 an unfollowed import is automatically given a type of ``Any``).
479
480 .. confval:: disallow_any_expr
481
482 :type: boolean
483 :default: False
484
485 Disallows all expressions in the module that have type ``Any``.
486
487 .. confval:: disallow_any_decorated
488
489 :type: boolean
490 :default: False
491
492 Disallows functions that have ``Any`` in their signature after decorator transformation.
493
494 .. confval:: disallow_any_explicit
495
496 :type: boolean
497 :default: False
498
499 Disallows explicit ``Any`` in type positions such as type annotations and generic
500 type parameters.
501
502 .. confval:: disallow_any_generics
503
504 :type: boolean
505 :default: False
506
507 Disallows usage of generic types that do not specify explicit type parameters.
508
509 .. confval:: disallow_subclassing_any
510
511 :type: boolean
512 :default: False
513
514 Disallows subclassing a value of type ``Any``.
515
516
517 Untyped definitions and calls
518 *****************************
519
520 For more information, see the :ref:`Untyped definitions and calls <untyped-definitions-and-calls>`
521 section of the command line docs.
522
523 .. confval:: disallow_untyped_calls
524
525 :type: boolean
526 :default: False
527
528 Disallows calling functions without type annotations from functions with type
529 annotations. Note that when used in per-module options, it enables/disables
530 this check **inside** the module(s) specified, not for functions that come
531 from that module(s), for example config like this:
532
533 .. code-block:: ini
534
535 [mypy]
536 disallow_untyped_calls = True
537
538 [mypy-some.library.*]
539 disallow_untyped_calls = False
540
541 will disable this check inside ``some.library``, not for your code that
542 imports ``some.library``. If you want to selectively disable this check for
543 all your code that imports ``some.library`` you should instead use
544 :confval:`untyped_calls_exclude`, for example:
545
546 .. code-block:: ini
547
548 [mypy]
549 disallow_untyped_calls = True
550 untyped_calls_exclude = some.library
551
552 .. confval:: untyped_calls_exclude
553
554 :type: comma-separated list of strings
555
556 Selectively excludes functions and methods defined in specific packages,
557 modules, and classes from action of :confval:`disallow_untyped_calls`.
558 This also applies to all submodules of packages (i.e. everything inside
559 a given prefix). Note, this option does not support per-file configuration,
560 the exclusions list is defined globally for all your code.
561
562 .. confval:: disallow_untyped_defs
563
564 :type: boolean
565 :default: False
566
567 Disallows defining functions without type annotations or with incomplete type
568 annotations (a superset of :confval:`disallow_incomplete_defs`).
569
570 For example, it would report an error for :code:`def f(a, b)` and :code:`def f(a: int, b)`.
571
572 .. confval:: disallow_incomplete_defs
573
574 :type: boolean
575 :default: False
576
577 Disallows defining functions with incomplete type annotations, while still
578 allowing entirely unannotated definitions.
579
580 For example, it would report an error for :code:`def f(a: int, b)` but not :code:`def f(a, b)`.
581
582 .. confval:: check_untyped_defs
583
584 :type: boolean
585 :default: False
586
587 Type-checks the interior of functions without type annotations.
588
589 .. confval:: disallow_untyped_decorators
590
591 :type: boolean
592 :default: False
593
594 Reports an error whenever a function with type annotations is decorated with a
595 decorator without annotations.
596
597
598 .. _config-file-none-and-optional-handling:
599
600 None and Optional handling
601 **************************
602
603 For more information, see the :ref:`None and Optional handling <none-and-optional-handling>`
604 section of the command line docs.
605
606 .. confval:: implicit_optional
607
608 :type: boolean
609 :default: False
610
611 Causes mypy to treat parameters with a ``None``
612 default value as having an implicit optional type (``T | None``).
613
614 **Note:** This was True by default in mypy versions 0.980 and earlier.
615
616 .. confval:: strict_optional
617
618 :type: boolean
619 :default: True
620
621 Effectively disables checking of optional
622 types and ``None`` values. With this option, mypy doesn't
623 generally check the use of ``None`` values -- it is treated
624 as compatible with every type.
625
626 .. warning::
627
628 ``strict_optional = false`` is evil. Avoid using it and definitely do
629 not use it without understanding what it does.
630
631
632 Configuring warnings
633 ********************
634
635 For more information, see the :ref:`Configuring warnings <configuring-warnings>`
636 section of the command line docs.
637
638 .. confval:: warn_redundant_casts
639
640 :type: boolean
641 :default: False
642
643 Warns about casting an expression to its inferred type.
644
645 This option may only be set in the global section (``[mypy]``).
646
647 .. confval:: warn_unused_ignores
648
649 :type: boolean
650 :default: False
651
652 Warns about unneeded ``# type: ignore`` comments.
653
654 .. confval:: warn_no_return
655
656 :type: boolean
657 :default: True
658
659 Shows errors for missing return statements on some execution paths.
660
661 .. confval:: warn_return_any
662
663 :type: boolean
664 :default: False
665
666 Shows a warning when returning a value with type ``Any`` from a function
667 declared with a non- ``Any`` return type.
668
669 .. confval:: warn_unreachable
670
671 :type: boolean
672 :default: False
673
674 Shows a warning when encountering any code inferred to be unreachable or
675 redundant after performing type analysis.
676
677 .. confval:: deprecated_calls_exclude
678
679 :type: comma-separated list of strings
680
681 Selectively excludes functions and methods defined in specific packages,
682 modules, and classes from the :ref:`deprecated<code-deprecated>` error code.
683 This also applies to all submodules of packages (i.e. everything inside
684 a given prefix). Note, this option does not support per-file configuration,
685 the exclusions list is defined globally for all your code.
686
687
688 Suppressing errors
689 ******************
690
691 Note: these configuration options are available in the config file only. There is
692 no analog available via the command line options.
693
694 .. confval:: ignore_errors
695
696 :type: boolean
697 :default: False
698
699 Ignores all non-fatal errors.
700
701
702 Miscellaneous strictness flags
703 ******************************
704
705 For more information, see the :ref:`Miscellaneous strictness flags <miscellaneous-strictness-flags>`
706 section of the command line docs.
707
708 .. confval:: allow_untyped_globals
709
710 :type: boolean
711 :default: False
712
713 Causes mypy to suppress errors caused by not being able to fully
714 infer the types of global and class variables.
715
716 .. confval:: allow_redefinition
717
718 :type: boolean
719 :default: False
720
721 By default, mypy won't allow a variable to be redefined with an
722 unrelated type. This flag enables the redefinition of unannotated
723 variables with an arbitrary type. This also requires
724 :confval:`local_partial_types`, which is enabled by default starting
725 from mypy 2.0. Example:
726
727 .. code-block:: python
728
729 def maybe_convert(n: int, b: bool) -> int | str:
730 if b:
731 x = str(n) # Assign "str"
732 else:
733 x = n # Assign "int"
734 # Type of "x" is "int | str" here.
735 return x
736
737 This also enables an unannotated variable to have different types in different
738 code locations:
739
740 .. code-block:: python
741
742 if check():
743 for x in range(n):
744 # Type of "x" is "int" here.
745 ...
746 else:
747 for x in ['a', 'b']:
748 # Type of "x" is "str" here.
749 ...
750
751 Function arguments are special, changing their type within function body
752 is allowed even if they are annotated, but that annotation is used to infer
753 types of r.h.s. of all subsequent assignments. Such middle-ground semantics
754 provides good balance for majority of common use cases. For example:
755
756 .. code-block:: python
757
758 def process(values: list[float]) -> None:
759 if not values:
760 values = [0, 0, 0]
761 reveal_type(values) # Revealed type is list[float]
762
763 Note: We are planning to turn this flag on by default in a future mypy
764 release.
765
766 .. confval:: allow_redefinition_new
767
768 :type: boolean
769 :default: False
770
771 Deprecated alias for :confval:`allow_redefinition`.
772
773 .. confval:: allow_redefinition_old
774
775 :type: boolean
776 :default: False
777
778 Allows variables to be redefined with an arbitrary type, as long as the redefinition
779 is in the same block and nesting level as the original definition.
780 Example where this can be useful:
781
782 .. code-block:: python
783
784 def process(items: list[str]) -> None:
785 # 'items' has type list[str]
786 items = [item.split() for item in items]
787 # 'items' now has type list[list[str]]
788
789 The variable must be used before it can be redefined:
790
791 .. code-block:: python
792
793 def process(items: list[str]) -> None:
794 items = "mypy" # invalid redefinition to str because the variable hasn't been used yet
795 print(items)
796 items = "100" # valid, items now has type str
797 items = int(items) # valid, items now has type int
798
799 .. confval:: local_partial_types
800
801 :type: boolean
802 :default: True
803
804 This prevents inferring a variable type from an empty container (such as a list or
805 a dictionary) created at module top level or class body and updated in
806 a function. This must be enabled when using the :ref:`mypy daemon <mypy_daemon>`.
807
808 .. confval:: disable_error_code
809
810 :type: comma-separated list of strings
811
812 Allows disabling one or multiple error codes globally.
813
814 .. confval:: enable_error_code
815
816 :type: comma-separated list of strings
817
818 Allows enabling one or multiple error codes globally.
819
820 Note: This option will override disabled error codes from the disable_error_code option.
821
822 .. confval:: extra_checks
823
824 :type: boolean
825 :default: False
826
827 This flag enables additional checks that are technically correct but may be impractical.
828 See :option:`mypy --extra-checks` for more info.
829
830 .. confval:: implicit_reexport
831
832 :type: boolean
833 :default: True
834
835 By default, imported values to a module are treated as exported and mypy allows
836 other modules to import them. When false, mypy will not re-export unless
837 the item is imported using from-as or is included in ``__all__``. Note that mypy
838 treats stub files as if this is always disabled. For example:
839
840 .. code-block:: python
841
842 # This won't re-export the value
843 from foo import bar
844 # This will re-export it as bar and allow other modules to import it
845 from foo import bar as bar
846 # This will also re-export bar
847 from foo import bar
848 __all__ = ['bar']
849
850 .. confval:: strict_equality
851
852 :type: boolean
853 :default: False
854
855 Prohibit equality checks, identity checks, and container checks between
856 non-overlapping types (except ``None``).
857
858 .. confval:: strict_equality_for_none
859
860 :type: boolean
861 :default: False
862
863 Include ``None`` in strict equality checks (requires :confval:`strict_equality`
864 to be activated).
865
866 .. confval:: strict_bytes
867
868 :type: boolean
869 :default: True
870
871 If disabled, mypy treats ``bytearray`` and ``memoryview`` as subtypes of ``bytes``.
872 This has been enabled by default since mypy 2.0.
873
874 .. confval:: strict
875
876 :type: boolean
877 :default: False
878
879 Enable all optional error checking flags. You can see the list of
880 flags enabled by strict mode in the full :option:`mypy --help`
881 output.
882
883 Note: the exact list of flags enabled by :confval:`strict` may
884 change over time.
885
886
887 Configuring error messages
888 **************************
889
890 For more information, see the :ref:`Configuring error messages <configuring-error-messages>`
891 section of the command line docs.
892
893 These options may only be set in the global section (``[mypy]``).
894
895 .. confval:: show_error_context
896
897 :type: boolean
898 :default: False
899
900 Prefixes each error with the relevant context.
901
902 .. confval:: show_column_numbers
903
904 :type: boolean
905 :default: False
906
907 Shows column numbers in error messages.
908
909 .. confval:: show_error_code_links
910
911 :type: boolean
912 :default: False
913
914 Shows documentation link to corresponding error code.
915
916 .. confval:: hide_error_codes
917
918 :type: boolean
919 :default: False
920
921 Hides error codes in error messages. See :ref:`error-codes` for more information.
922
923 .. confval:: pretty
924
925 :type: boolean
926 :default: False
927
928 Use visually nicer output in error messages: use soft word wrap,
929 show source code snippets, and show error location markers.
930
931 .. confval:: color_output
932
933 :type: boolean
934 :default: True
935
936 Shows error messages with color enabled.
937
938 .. confval:: error_summary
939
940 :type: boolean
941 :default: True
942
943 Shows a short summary line after error messages.
944
945 .. confval:: show_absolute_path
946
947 :type: boolean
948 :default: False
949
950 Show absolute paths to files.
951
952 Incremental mode
953 ****************
954
955 These options may only be set in the global section (``[mypy]``).
956
957 .. confval:: incremental
958
959 :type: boolean
960 :default: True
961
962 Enables :ref:`incremental mode <incremental>`.
963
964 .. confval:: cache_dir
965
966 :type: string
967 :default: ``.mypy_cache``
968
969 Specifies the location where mypy stores incremental cache info.
970 User home directory and environment variables will be expanded.
971 This setting will be overridden by the ``MYPY_CACHE_DIR`` environment
972 variable.
973
974 Note that the cache is only read when incremental mode is enabled
975 but is always written to, unless the value is set to ``/dev/null``
976 (UNIX) or ``nul`` (Windows).
977
978 .. confval:: sqlite_cache
979
980 :type: boolean
981 :default: True
982
983 Use an `SQLite`_ database to store the cache.
984
985 .. confval:: cache_fine_grained
986
987 :type: boolean
988 :default: False
989
990 Include fine-grained dependency information in the cache for the mypy daemon.
991
992 .. confval:: skip_version_check
993
994 :type: boolean
995 :default: False
996
997 Makes mypy use incremental cache data even if it was generated by a
998 different version of mypy. (By default, mypy will perform a version
999 check and regenerate the cache if it was written by older versions of mypy.)
1000
1001 .. confval:: skip_cache_mtime_checks
1002
1003 :type: boolean
1004 :default: False
1005
1006 Skip cache internal consistency checks based on mtime.
1007
1008
1009 Parallel type-checking configuration
1010 ************************************
1011
1012 These options may only be set in the global section (``[mypy]``).
1013
1014 .. confval:: num_workers
1015
1016 :type: integer
1017 :default: 0
1018
1019 Use specific number of parallel worker processes for type-checking, see
1020 :ref:`parallel type-checking <parallel>` for more details.
1021 This setting will be overridden by the ``MYPY_NUM_WORKERS`` environment
1022 variable.
1023
1024
1025 Advanced options
1026 ****************
1027
1028 These options may only be set in the global section (``[mypy]``).
1029
1030 .. confval:: plugins
1031
1032 :type: comma-separated list of strings
1033
1034 A comma-separated list of mypy plugins. See :ref:`extending-mypy-using-plugins`.
1035
1036 .. confval:: pdb
1037
1038 :type: boolean
1039 :default: False
1040
1041 Invokes :mod:`pdb` on fatal error.
1042
1043 .. confval:: show_traceback
1044
1045 :type: boolean
1046 :default: False
1047
1048 Shows traceback on fatal error.
1049
1050 .. confval:: raise_exceptions
1051
1052 :type: boolean
1053 :default: False
1054
1055 Raise exception on fatal error.
1056
1057 .. confval:: custom_typing_module
1058
1059 :type: string
1060
1061 Specifies a custom module to use as a substitute for the :py:mod:`typing` module.
1062
1063 .. confval:: custom_typeshed_dir
1064
1065 :type: string
1066
1067 This specifies the directory where mypy looks for standard library typeshed
1068 stubs, instead of the typeshed that ships with mypy. This is
1069 primarily intended to make it easier to test typeshed changes before
1070 submitting them upstream, but also allows you to use a forked version of
1071 typeshed.
1072
1073 User home directory and environment variables will be expanded.
1074
1075 Note that this doesn't affect third-party library stubs. To test third-party stubs,
1076 for example try ``MYPYPATH=stubs/six mypy ...``.
1077
1078 .. confval:: warn_incomplete_stub
1079
1080 :type: boolean
1081 :default: False
1082
1083 Warns about missing type annotations in typeshed. This is only relevant
1084 in combination with :confval:`disallow_untyped_defs` or :confval:`disallow_incomplete_defs`.
1085
1086 .. confval:: native_parser
1087
1088 :type: boolean
1089 :default: False
1090
1091 This enables fast Rust-based parser that parses directly to mypy AST.
1092 It will become the default parser in one of the next mypy releases.
1093
1094
1095 Report generation
1096 *****************
1097
1098 If these options are set, mypy will generate a report in the specified
1099 format into the specified directory.
1100
1101 .. warning::
1102
1103 Generating reports disables incremental mode and can significantly slow down
1104 your workflow. It is recommended to enable reporting only for specific runs
1105 (e.g. in CI).
1106
1107 .. confval:: any_exprs_report
1108
1109 :type: string
1110
1111 Causes mypy to generate a text file report documenting how many
1112 expressions of type ``Any`` are present within your codebase.
1113
1114 .. confval:: cobertura_xml_report
1115
1116 :type: string
1117
1118 Causes mypy to generate a Cobertura XML type checking coverage report.
1119
1120 To generate this report, you must either manually install the `lxml`_
1121 library or specify mypy installation with the setuptools extra
1122 ``mypy[reports]``.
1123
1124 .. confval:: html_report / xslt_html_report
1125
1126 :type: string
1127
1128 Causes mypy to generate an HTML type checking coverage report.
1129
1130 To generate this report, you must either manually install the `lxml`_
1131 library or specify mypy installation with the setuptools extra
1132 ``mypy[reports]``.
1133
1134 .. confval:: linecount_report
1135
1136 :type: string
1137
1138 Causes mypy to generate a text file report documenting the functions
1139 and lines that are typed and untyped within your codebase.
1140
1141 .. confval:: linecoverage_report
1142
1143 :type: string
1144
1145 Causes mypy to generate a JSON file that maps each source file's
1146 absolute filename to a list of line numbers that belong to typed
1147 functions in that file.
1148
1149 .. confval:: lineprecision_report
1150
1151 :type: string
1152
1153 Causes mypy to generate a flat text file report with per-module
1154 statistics of how many lines are typechecked etc.
1155
1156 .. confval:: txt_report / xslt_txt_report
1157
1158 :type: string
1159
1160 Causes mypy to generate a text file type checking coverage report.
1161
1162 To generate this report, you must either manually install the `lxml`_
1163 library or specify mypy installation with the setuptools extra
1164 ``mypy[reports]``.
1165
1166 .. confval:: xml_report
1167
1168 :type: string
1169
1170 Causes mypy to generate an XML type checking coverage report.
1171
1172 To generate this report, you must either manually install the `lxml`_
1173 library or specify mypy installation with the setuptools extra
1174 ``mypy[reports]``.
1175
1176
1177 Miscellaneous
1178 *************
1179
1180 These options may only be set in the global section (``[mypy]``).
1181
1182 .. confval:: junit_xml
1183
1184 :type: string
1185
1186 Causes mypy to generate a JUnit XML test result document with
1187 type checking results. This can make it easier to integrate mypy
1188 with continuous integration (CI) tools.
1189
1190 .. confval:: junit_format
1191
1192 :type: string
1193 :default: ``global``
1194
1195 If junit_xml is set, specifies format.
1196 global (default): single test with all errors;
1197 per_file: one test entry per file with failures.
1198
1199 .. confval:: scripts_are_modules
1200
1201 :type: boolean
1202 :default: False
1203
1204 Makes script ``x`` become module ``x`` instead of ``__main__``. This is
1205 useful when checking multiple scripts in a single run.
1206
1207 .. confval:: warn_unused_configs
1208
1209 :type: boolean
1210 :default: False
1211
1212 Warns about per-module sections in the config file that do not
1213 match any files processed when invoking mypy.
1214 (This requires turning off incremental mode using :confval:`incremental = False <incremental>`.)
1215
1216 .. confval:: verbosity
1217
1218 :type: integer
1219 :default: 0
1220
1221 Controls how much debug output will be generated. Higher numbers are more verbose.
1222
1223
1224 .. _using-a-pyproject-toml:
1225
1226 Using a pyproject.toml file
1227 ***************************
1228
1229 Instead of using a ``mypy.ini`` file, a ``pyproject.toml`` file (as specified by
1230 `PEP 518`_) may be used instead. A few notes on doing so:
1231
1232 * The ``[mypy]`` section should have ``tool.`` prepended to its name:
1233
1234 * I.e., ``[mypy]`` would become ``[tool.mypy]``
1235
1236 * The module specific sections should be moved into ``[[tool.mypy.overrides]]`` sections:
1237
1238 * For example, ``[mypy-packagename]`` would become:
1239
1240 .. code-block:: toml
1241
1242 [[tool.mypy.overrides]]
1243 module = 'packagename'
1244 ...
1245
1246 * Multi-module specific sections can be moved into a single ``[[tool.mypy.overrides]]`` section with a
1247 module property set to an array of modules:
1248
1249 * For example, ``[mypy-packagename,packagename2]`` would become:
1250
1251 .. code-block:: toml
1252
1253 [[tool.mypy.overrides]]
1254 module = [
1255 'packagename',
1256 'packagename2'
1257 ]
1258 ...
1259
1260 * The following care should be given to values in the ``pyproject.toml`` files as compared to ``ini`` files:
1261
1262 * Strings must be wrapped in double quotes, or single quotes if the string contains special characters
1263
1264 * Boolean values should be all lower case
1265
1266 Please see the `TOML Documentation`_ for more details and information on
1267 what is allowed in a ``toml`` file. See `PEP 518`_ for more information on the layout
1268 and structure of the ``pyproject.toml`` file.
1269
1270 Example ``pyproject.toml``
1271 **************************
1272
1273 Here is an example of a ``pyproject.toml`` file. To use this config file, place it at the root
1274 of your repo (or append it to the end of an existing ``pyproject.toml`` file) and run mypy.
1275
1276 .. code-block:: toml
1277
1278 # mypy global options:
1279
1280 [tool.mypy]
1281 python_version = "3.10"
1282 warn_return_any = true
1283 warn_unused_configs = true
1284 exclude = [
1285 '^file1\.py$', # TOML literal string (single-quotes, no escaping necessary)
1286 "^file2\\.py$", # TOML basic string (double-quotes, backslash and other characters need escaping)
1287 ]
1288
1289 # mypy per-module options:
1290
1291 [[tool.mypy.overrides]]
1292 module = "mycode.foo.*"
1293 disallow_untyped_defs = true
1294
1295 [[tool.mypy.overrides]]
1296 module = "mycode.bar"
1297 warn_return_any = false
1298
1299 [[tool.mypy.overrides]]
1300 module = [
1301 "somelibrary",
1302 "some_other_library"
1303 ]
1304 ignore_missing_imports = true
1305
1306 .. _lxml: https://pypi.org/project/lxml/
1307 .. _SQLite: https://www.sqlite.org/
1308 .. _PEP 518: https://www.python.org/dev/peps/pep-0518/
1309 .. _TOML Documentation: https://toml.io/