| 1 |
.. _existing-code: |
| 2 |
|
| 3 |
Using mypy with an existing codebase |
| 4 |
==================================== |
| 5 |
|
| 6 |
This section explains how to get started using mypy with an existing, |
| 7 |
significant codebase that has little or no type annotations. If you are |
| 8 |
a beginner, you can skip this section. |
| 9 |
|
| 10 |
Start small |
| 11 |
----------- |
| 12 |
|
| 13 |
If your codebase is large, pick a subset of your codebase (say, 5,000 to 50,000 |
| 14 |
lines) and get mypy to run successfully only on this subset at first, *before |
| 15 |
adding annotations*. This should be doable in a day or two. The sooner you get |
| 16 |
some form of mypy passing on your codebase, the sooner you benefit. |
| 17 |
|
| 18 |
You'll likely need to fix some mypy errors, either by inserting |
| 19 |
annotations requested by mypy or by adding ``# type: ignore`` |
| 20 |
comments to silence errors you don't want to fix now. |
| 21 |
|
| 22 |
We'll mention some tips for getting mypy passing on your codebase in various |
| 23 |
sections below. |
| 24 |
|
| 25 |
Run mypy consistently and prevent regressions |
| 26 |
--------------------------------------------- |
| 27 |
|
| 28 |
Make sure all developers on your codebase run mypy the same way. |
| 29 |
One way to ensure this is adding a small script with your mypy |
| 30 |
invocation to your codebase, or adding your mypy invocation to |
| 31 |
existing tools you use to run tests, like ``tox``. |
| 32 |
|
| 33 |
* Make sure everyone runs mypy with the same options. Checking a mypy |
| 34 |
:ref:`configuration file <config-file>` into your codebase is the |
| 35 |
easiest way to do this. |
| 36 |
|
| 37 |
* Make sure everyone type checks the same set of files. See |
| 38 |
:ref:`specifying-code-to-be-checked` for details. |
| 39 |
|
| 40 |
* Make sure everyone runs mypy with the same version of mypy, for instance |
| 41 |
by pinning mypy with the rest of your dev requirements. |
| 42 |
|
| 43 |
In particular, you'll want to make sure to run mypy as part of your |
| 44 |
Continuous Integration (CI) system as soon as possible. This will |
| 45 |
prevent new type errors from being introduced into your codebase. |
| 46 |
|
| 47 |
A simple CI script could look something like this: |
| 48 |
|
| 49 |
.. code-block:: text |
| 50 |
|
| 51 |
python3 -m pip install mypy==1.8 |
| 52 |
# Run your standardised mypy invocation, e.g. |
| 53 |
mypy my_project |
| 54 |
# This could also look like `scripts/run_mypy.sh`, `tox run -e mypy`, `make mypy`, etc |
| 55 |
|
| 56 |
Ignoring errors from certain modules |
| 57 |
------------------------------------ |
| 58 |
|
| 59 |
By default mypy will follow imports in your code and try to check everything. |
| 60 |
This means even if you only pass in a few files to mypy, it may still process a |
| 61 |
large number of imported files. This could potentially result in lots of errors |
| 62 |
you don't want to deal with at the moment. |
| 63 |
|
| 64 |
One way to deal with this is to ignore errors in modules you aren't yet ready to |
| 65 |
type check. The :confval:`ignore_errors` option is useful for this, for instance, |
| 66 |
if you aren't yet ready to deal with errors from ``package_to_fix_later``: |
| 67 |
|
| 68 |
.. code-block:: text |
| 69 |
|
| 70 |
[mypy-package_to_fix_later.*] |
| 71 |
ignore_errors = True |
| 72 |
|
| 73 |
You could even invert this, by setting ``ignore_errors = True`` in your global |
| 74 |
config section and only enabling error reporting with ``ignore_errors = False`` |
| 75 |
for the set of modules you are ready to type check. |
| 76 |
|
| 77 |
The per-module configuration that mypy's configuration file allows can be |
| 78 |
extremely useful. Many configuration options can be enabled or disabled |
| 79 |
only for specific modules. In particular, you can also enable or disable |
| 80 |
various error codes on a per-module basis, see :ref:`error-codes`. |
| 81 |
|
| 82 |
Fixing errors related to imports |
| 83 |
-------------------------------- |
| 84 |
|
| 85 |
A common class of error you will encounter is errors from mypy about modules |
| 86 |
that it can't find, that don't have types, or don't have stub files: |
| 87 |
|
| 88 |
.. code-block:: text |
| 89 |
|
| 90 |
core/config.py:7: error: Cannot find implementation or library stub for module named 'frobnicate' |
| 91 |
core/model.py:9: error: Cannot find implementation or library stub for module named 'acme' |
| 92 |
... |
| 93 |
|
| 94 |
Sometimes these can be fixed by installing the relevant packages or |
| 95 |
stub libraries in the environment you're running ``mypy`` in. |
| 96 |
|
| 97 |
See :ref:`fix-missing-imports` for a complete reference on these errors |
| 98 |
and the ways in which you can fix them. |
| 99 |
|
| 100 |
You'll likely find that you want to suppress all errors from importing |
| 101 |
a given module that doesn't have types. If you only import that module |
| 102 |
in one or two places, you can use ``# type: ignore`` comments. For example, |
| 103 |
here we ignore an error about a third-party module ``frobnicate`` that |
| 104 |
doesn't have stubs using ``# type: ignore``: |
| 105 |
|
| 106 |
.. code-block:: python |
| 107 |
|
| 108 |
import frobnicate # type: ignore |
| 109 |
... |
| 110 |
frobnicate.initialize() # OK (but not checked) |
| 111 |
|
| 112 |
But if you import the module in many places, this becomes unwieldy. In this |
| 113 |
case, we recommend using a :ref:`configuration file <config-file>`. For example, |
| 114 |
to disable errors about importing ``frobnicate`` and ``acme`` everywhere in your |
| 115 |
codebase, use a config like this: |
| 116 |
|
| 117 |
.. code-block:: text |
| 118 |
|
| 119 |
[mypy-frobnicate.*] |
| 120 |
ignore_missing_imports = True |
| 121 |
|
| 122 |
[mypy-acme.*] |
| 123 |
ignore_missing_imports = True |
| 124 |
|
| 125 |
If you get a large number of errors, you may want to ignore all errors |
| 126 |
about missing imports, for instance by setting |
| 127 |
:option:`--disable-error-code=import-untyped <mypy --ignore-missing-imports>`. |
| 128 |
or setting :confval:`ignore_missing_imports` to true globally. |
| 129 |
This can hide errors later on, so we recommend avoiding this |
| 130 |
if possible. |
| 131 |
|
| 132 |
Finally, mypy allows fine-grained control over specific import following |
| 133 |
behaviour. It's very easy to silently shoot yourself in the foot when playing |
| 134 |
around with these, so this should be a last resort. For more |
| 135 |
details, look :ref:`here <follow-imports>`. |
| 136 |
|
| 137 |
Prioritise annotating widely imported modules |
| 138 |
--------------------------------------------- |
| 139 |
|
| 140 |
Most projects have some widely imported modules, such as utilities or |
| 141 |
model classes. It's a good idea to annotate these pretty early on, |
| 142 |
since this allows code using these modules to be type checked more |
| 143 |
effectively. |
| 144 |
|
| 145 |
Mypy is designed to support gradual typing, i.e. letting you add annotations at |
| 146 |
your own pace, so it's okay to leave some of these modules unannotated. The more |
| 147 |
you annotate, the more useful mypy will be, but even a little annotation |
| 148 |
coverage is useful. |
| 149 |
|
| 150 |
Write annotations as you go |
| 151 |
--------------------------- |
| 152 |
|
| 153 |
Consider adding something like these in your code style |
| 154 |
conventions: |
| 155 |
|
| 156 |
1. Developers should add annotations for any new code. |
| 157 |
2. It's also encouraged to write annotations when you modify existing code. |
| 158 |
|
| 159 |
This way you'll gradually increase annotation coverage in your |
| 160 |
codebase without much effort. |
| 161 |
|
| 162 |
Automate annotation of legacy code |
| 163 |
---------------------------------- |
| 164 |
|
| 165 |
There are tools for automatically adding draft annotations based on simple |
| 166 |
static analysis or on type profiles collected at runtime. Tools include |
| 167 |
:doc:`monkeytype:index`, `autotyping`_ and `PyAnnotate`_. |
| 168 |
|
| 169 |
A simple approach is to collect types from test runs. This may work |
| 170 |
well if your test coverage is good (and if your tests aren't very |
| 171 |
slow). |
| 172 |
|
| 173 |
Another approach is to enable type collection for a small, random |
| 174 |
fraction of production network requests. This clearly requires more |
| 175 |
care, as type collection could impact the reliability or the |
| 176 |
performance of your service. |
| 177 |
|
| 178 |
.. _getting-to-strict: |
| 179 |
|
| 180 |
Introduce stricter options |
| 181 |
-------------------------- |
| 182 |
|
| 183 |
Mypy is very configurable. Once you get started with static typing, you may want |
| 184 |
to explore the various strictness options mypy provides to catch more bugs. For |
| 185 |
example, you can ask mypy to require annotations for all functions in certain |
| 186 |
modules to avoid accidentally introducing code that won't be type checked using |
| 187 |
:confval:`disallow_untyped_defs`. Refer to :ref:`config-file` for the details. |
| 188 |
|
| 189 |
An excellent goal to aim for is to have your codebase pass when run against ``mypy --strict``. |
| 190 |
This basically ensures that you will never have a type related error without an explicit |
| 191 |
circumvention somewhere (such as a ``# type: ignore`` comment). |
| 192 |
|
| 193 |
The following config is equivalent to ``--strict`` (as of mypy 1.0): |
| 194 |
|
| 195 |
.. code-block:: text |
| 196 |
|
| 197 |
# Start off with these |
| 198 |
warn_unused_configs = True |
| 199 |
warn_redundant_casts = True |
| 200 |
warn_unused_ignores = True |
| 201 |
|
| 202 |
# Getting this passing should be easy |
| 203 |
strict_equality = True |
| 204 |
|
| 205 |
# Strongly recommend enabling this one as soon as you can |
| 206 |
check_untyped_defs = True |
| 207 |
|
| 208 |
# These shouldn't be too much additional work, but may be tricky to |
| 209 |
# get passing if you use a lot of untyped libraries |
| 210 |
disallow_subclassing_any = True |
| 211 |
disallow_untyped_decorators = True |
| 212 |
disallow_any_generics = True |
| 213 |
|
| 214 |
# These next few are various gradations of forcing use of type annotations |
| 215 |
disallow_untyped_calls = True |
| 216 |
disallow_incomplete_defs = True |
| 217 |
disallow_untyped_defs = True |
| 218 |
|
| 219 |
# This one isn't too hard to get passing, but return on investment is lower |
| 220 |
no_implicit_reexport = True |
| 221 |
|
| 222 |
# This one can be tricky to get passing if you use a lot of untyped libraries |
| 223 |
warn_return_any = True |
| 224 |
|
| 225 |
# This one is a catch-all flag for the rest of strict checks that are technically |
| 226 |
# correct but may not be practical |
| 227 |
extra_checks = True |
| 228 |
|
| 229 |
Note that you can also start with ``--strict`` and subtract, for instance: |
| 230 |
|
| 231 |
.. code-block:: text |
| 232 |
|
| 233 |
strict = True |
| 234 |
warn_return_any = False |
| 235 |
|
| 236 |
Remember that many of these options can be enabled on a per-module basis. For instance, |
| 237 |
you may want to enable ``disallow_untyped_defs`` for modules which you've completed |
| 238 |
annotations for, in order to prevent new code from being added without annotations. |
| 239 |
|
| 240 |
And if you want, it doesn't stop at ``--strict``. Mypy has additional checks |
| 241 |
that are not part of ``--strict`` that can be useful. See the complete |
| 242 |
:ref:`command-line` reference and :ref:`error-codes-optional`. |
| 243 |
|
| 244 |
Speed up mypy runs |
| 245 |
------------------ |
| 246 |
|
| 247 |
You can use :ref:`mypy daemon <mypy_daemon>` to get much faster |
| 248 |
incremental mypy runs. The larger your project is, the more useful |
| 249 |
this will be. If your project has at least 100,000 lines of code or |
| 250 |
so, you may also want to set up :ref:`remote caching <remote-cache>` |
| 251 |
for further speedups. |
| 252 |
|
| 253 |
.. _PyAnnotate: https://github.com/dropbox/pyannotate |
| 254 |
.. _autotyping: https://github.com/JelleZijlstra/autotyping |