| 1 |
.. _getting-started: |
| 2 |
|
| 3 |
Getting started |
| 4 |
=============== |
| 5 |
|
| 6 |
This chapter introduces some core concepts of mypy, including function |
| 7 |
annotations, the :py:mod:`typing` module, stub files, and more. |
| 8 |
|
| 9 |
If you're looking for a quick intro, see the |
| 10 |
:ref:`mypy cheatsheet <cheat-sheet-py3>`. |
| 11 |
|
| 12 |
If you're unfamiliar with the concepts of static and dynamic type checking, |
| 13 |
be sure to read this chapter carefully, as the rest of the documentation |
| 14 |
may not make much sense otherwise. |
| 15 |
|
| 16 |
Installing and running mypy |
| 17 |
*************************** |
| 18 |
|
| 19 |
Mypy requires Python 3.10 or later to run. You can install mypy using pip: |
| 20 |
|
| 21 |
.. code-block:: shell |
| 22 |
|
| 23 |
$ python3 -m pip install mypy |
| 24 |
|
| 25 |
Once mypy is installed, run it by using the ``mypy`` tool: |
| 26 |
|
| 27 |
.. code-block:: shell |
| 28 |
|
| 29 |
$ mypy program.py |
| 30 |
|
| 31 |
This command makes mypy *type check* your ``program.py`` file and print |
| 32 |
out any errors it finds. Mypy will type check your code *statically*: this |
| 33 |
means that it will check for errors without ever running your code, just |
| 34 |
like a linter. |
| 35 |
|
| 36 |
This also means that you are always free to ignore the errors mypy reports, |
| 37 |
if you so wish. You can always use the Python interpreter to run your code, |
| 38 |
even if mypy reports errors. |
| 39 |
|
| 40 |
However, if you try directly running mypy on your existing Python code, it |
| 41 |
will most likely report little to no errors. This is a feature! It makes it |
| 42 |
easy to adopt mypy incrementally. |
| 43 |
|
| 44 |
In order to get useful diagnostics from mypy, you must add *type annotations* |
| 45 |
to your code. See the section below for details. |
| 46 |
|
| 47 |
.. _getting-started-dynamic-vs-static: |
| 48 |
|
| 49 |
Dynamic vs static typing |
| 50 |
************************ |
| 51 |
|
| 52 |
A function without type annotations is considered to be *dynamically typed* by mypy: |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
def greeting(name): |
| 57 |
return 'Hello ' + name |
| 58 |
|
| 59 |
By default, mypy will **not** type check dynamically typed functions. This means |
| 60 |
that with a few exceptions, mypy will not report any errors with regular unannotated Python. |
| 61 |
|
| 62 |
This is the case even if you misuse the function! |
| 63 |
|
| 64 |
.. code-block:: python |
| 65 |
|
| 66 |
def greeting(name): |
| 67 |
return 'Hello ' + name |
| 68 |
|
| 69 |
# These calls will fail when the program runs, but mypy does not report an error |
| 70 |
# because "greeting" does not have type annotations. |
| 71 |
greeting(123) |
| 72 |
greeting(b"Alice") |
| 73 |
|
| 74 |
We can get mypy to detect these kinds of bugs by adding *type annotations* (also |
| 75 |
known as *type hints*). For example, you can tell mypy that ``greeting`` both accepts |
| 76 |
and returns a string like so: |
| 77 |
|
| 78 |
.. code-block:: python |
| 79 |
|
| 80 |
# The "name: str" annotation says that the "name" argument should be a string |
| 81 |
# The "-> str" annotation says that "greeting" will return a string |
| 82 |
def greeting(name: str) -> str: |
| 83 |
return 'Hello ' + name |
| 84 |
|
| 85 |
This function is now *statically typed*: mypy will use the provided type hints |
| 86 |
to detect incorrect use of the ``greeting`` function and incorrect use of |
| 87 |
variables within the ``greeting`` function. For example: |
| 88 |
|
| 89 |
.. code-block:: python |
| 90 |
|
| 91 |
def greeting(name: str) -> str: |
| 92 |
return 'Hello ' + name |
| 93 |
|
| 94 |
greeting(3) # Argument 1 to "greeting" has incompatible type "int"; expected "str" |
| 95 |
greeting(b'Alice') # Argument 1 to "greeting" has incompatible type "bytes"; expected "str" |
| 96 |
greeting("World!") # No error |
| 97 |
|
| 98 |
def bad_greeting(name: str) -> str: |
| 99 |
return 'Hello ' * name # Unsupported operand types for * ("str" and "str") |
| 100 |
|
| 101 |
Being able to pick whether you want a function to be dynamically or statically |
| 102 |
typed can be very helpful. For example, if you are migrating an existing |
| 103 |
Python codebase to use static types, it's usually easier to migrate by incrementally |
| 104 |
adding type hints to your code rather than adding them all at once. Similarly, |
| 105 |
when you are prototyping a new feature, it may be convenient to initially implement |
| 106 |
the code using dynamic typing and only add type hints later once the code is more stable. |
| 107 |
|
| 108 |
Once you are finished migrating or prototyping your code, you can make mypy warn you |
| 109 |
if you add a dynamic function by mistake by using the :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>` |
| 110 |
flag. You can also get mypy to provide some limited checking of dynamically typed |
| 111 |
functions by using the :option:`--check-untyped-defs <mypy --check-untyped-defs>` flag. |
| 112 |
See :ref:`command-line` for more information on configuring mypy. |
| 113 |
|
| 114 |
Strict mode and configuration |
| 115 |
***************************** |
| 116 |
|
| 117 |
Mypy has a *strict mode* that enables a number of additional checks, |
| 118 |
like :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`. |
| 119 |
|
| 120 |
If you run mypy with the :option:`--strict <mypy --strict>` flag, you |
| 121 |
will basically never get a type related error at runtime without a corresponding |
| 122 |
mypy error, unless you explicitly circumvent mypy somehow. |
| 123 |
|
| 124 |
However, this flag will probably be too aggressive if you are trying |
| 125 |
to add static types to a large, existing codebase. See :ref:`existing-code` |
| 126 |
for suggestions on how to handle that case. |
| 127 |
|
| 128 |
Mypy is very configurable, so you can start with using ``--strict`` |
| 129 |
and toggle off individual checks. For instance, if you use many third |
| 130 |
party libraries that do not have types, |
| 131 |
:option:`--ignore-missing-imports <mypy --ignore-missing-imports>` |
| 132 |
may be useful. See :ref:`getting-to-strict` for how to build up to ``--strict``. |
| 133 |
|
| 134 |
See :ref:`command-line` and :ref:`config-file` for a complete reference on |
| 135 |
configuration options. |
| 136 |
|
| 137 |
More complex types |
| 138 |
****************** |
| 139 |
|
| 140 |
So far, we've added type hints that use only basic concrete types like |
| 141 |
``str`` and ``float``. What if we want to express more complex types, |
| 142 |
such as "a list of strings" or "an iterable of ints"? |
| 143 |
|
| 144 |
For example, to indicate that some function can accept a list of |
| 145 |
strings, use the ``list[str]`` type (Python 3.9 and later): |
| 146 |
|
| 147 |
.. code-block:: python |
| 148 |
|
| 149 |
def greet_all(names: list[str]) -> None: |
| 150 |
for name in names: |
| 151 |
print('Hello ' + name) |
| 152 |
|
| 153 |
names = ["Alice", "Bob", "Charlie"] |
| 154 |
ages = [10, 20, 30] |
| 155 |
|
| 156 |
greet_all(names) # Ok! |
| 157 |
greet_all(ages) # Error due to incompatible types |
| 158 |
|
| 159 |
The :py:class:`list` type is an example of something called a *generic type*: it can |
| 160 |
accept one or more *type parameters*. In this case, we *parameterized* :py:class:`list` |
| 161 |
by writing ``list[str]``. This lets mypy know that ``greet_all`` accepts specifically |
| 162 |
lists containing strings, and not lists containing ints or any other type. |
| 163 |
|
| 164 |
In the above examples, the type signature is perhaps a little too rigid. |
| 165 |
After all, there's no reason why this function must accept *specifically* a list -- |
| 166 |
it would run just fine if you were to pass in a tuple, a set, or any other custom iterable. |
| 167 |
|
| 168 |
You can express this idea using :py:class:`collections.abc.Iterable`: |
| 169 |
|
| 170 |
.. code-block:: python |
| 171 |
|
| 172 |
from collections.abc import Iterable # or "from typing import Iterable" |
| 173 |
|
| 174 |
def greet_all(names: Iterable[str]) -> None: |
| 175 |
for name in names: |
| 176 |
print('Hello ' + name) |
| 177 |
|
| 178 |
This behavior is actually a fundamental aspect of the PEP 484 type system: when |
| 179 |
we annotate some variable with a type ``T``, we are actually telling mypy that |
| 180 |
variable can be assigned an instance of ``T``, or an instance of a *subtype* of ``T``. |
| 181 |
That is, ``list[str]`` is a subtype of ``Iterable[str]``. |
| 182 |
|
| 183 |
This also applies to inheritance, so if you have a class ``Child`` that inherits from |
| 184 |
``Parent``, then a value of type ``Child`` can be assigned to a variable of type ``Parent``. |
| 185 |
For example, a ``RuntimeError`` instance can be passed to a function that is annotated |
| 186 |
as taking an ``Exception``. |
| 187 |
|
| 188 |
As another example, suppose you want to write a function that can accept *either* |
| 189 |
ints or strings, but no other types. You can express this using a |
| 190 |
union type. For example, ``int`` is a subtype of ``int | str``: |
| 191 |
|
| 192 |
.. code-block:: python |
| 193 |
|
| 194 |
def normalize_id(user_id: int | str) -> str: |
| 195 |
if isinstance(user_id, int): |
| 196 |
return f'user-{100_000 + user_id}' |
| 197 |
else: |
| 198 |
return user_id |
| 199 |
|
| 200 |
The :py:mod:`typing` module contains many other useful types. |
| 201 |
|
| 202 |
For a quick overview, look through the :ref:`mypy cheatsheet <cheat-sheet-py3>`. |
| 203 |
|
| 204 |
For a detailed overview (including information on how to make your own |
| 205 |
generic types or your own type aliases), look through the |
| 206 |
:ref:`type system reference <overview-type-system-reference>`. |
| 207 |
|
| 208 |
.. note:: |
| 209 |
|
| 210 |
When adding types, the convention is to import types |
| 211 |
using the form ``from typing import <name>`` (as opposed to doing |
| 212 |
just ``import typing`` or ``import typing as t`` or ``from typing import *``). |
| 213 |
|
| 214 |
For brevity, we often omit imports from :py:mod:`typing` or :py:mod:`collections.abc` |
| 215 |
in code examples, but mypy will give an error if you use types such as |
| 216 |
:py:class:`~collections.abc.Iterable` without first importing them. |
| 217 |
|
| 218 |
.. note:: |
| 219 |
|
| 220 |
In some examples we use capitalized variants of types, such as |
| 221 |
``List``, and sometimes we use plain ``list``. They are equivalent, |
| 222 |
but the prior variant is needed if you are using Python 3.8 or earlier. |
| 223 |
|
| 224 |
Local type inference |
| 225 |
******************** |
| 226 |
|
| 227 |
Once you have added type hints to a function (i.e. made it statically typed), |
| 228 |
mypy will automatically type check that function's body. While doing so, |
| 229 |
mypy will try and *infer* as many details as possible. |
| 230 |
|
| 231 |
We saw an example of this in the ``normalize_id`` function above -- mypy understands |
| 232 |
basic :py:func:`isinstance <isinstance>` checks and so can infer that the ``user_id`` variable was of |
| 233 |
type ``int`` in the if-branch and of type ``str`` in the else-branch. |
| 234 |
|
| 235 |
As another example, consider the following function. Mypy can type check this function |
| 236 |
without a problem: it will use the available context and deduce that ``output`` must be |
| 237 |
of type ``list[float]`` and that ``num`` must be of type ``float``: |
| 238 |
|
| 239 |
.. code-block:: python |
| 240 |
|
| 241 |
def nums_below(numbers: Iterable[float], limit: float) -> list[float]: |
| 242 |
output = [] |
| 243 |
for num in numbers: |
| 244 |
if num < limit: |
| 245 |
output.append(num) |
| 246 |
return output |
| 247 |
|
| 248 |
For more details, see :ref:`type-inference-and-annotations`. |
| 249 |
|
| 250 |
Types from libraries |
| 251 |
******************** |
| 252 |
|
| 253 |
Mypy can also understand how to work with types from libraries that you use. |
| 254 |
|
| 255 |
For instance, mypy comes out of the box with an intimate knowledge of the |
| 256 |
Python standard library. For example, here is a function which uses the |
| 257 |
``Path`` object from the :doc:`pathlib standard library module <python:library/pathlib>`: |
| 258 |
|
| 259 |
.. code-block:: python |
| 260 |
|
| 261 |
from pathlib import Path |
| 262 |
|
| 263 |
def load_template(template_path: Path, name: str) -> str: |
| 264 |
# Mypy knows that `template_path` has a `read_text` method that returns a str |
| 265 |
template = template_path.read_text() |
| 266 |
# ...so it understands this line type checks |
| 267 |
return template.replace('USERNAME', name) |
| 268 |
|
| 269 |
If a third party library you use :ref:`declares support for type checking <installed-packages>`, |
| 270 |
mypy will type check your use of that library based on the type hints |
| 271 |
it contains. |
| 272 |
|
| 273 |
However, if the third party library does not have type hints, mypy will |
| 274 |
complain about missing type information. |
| 275 |
|
| 276 |
.. code-block:: text |
| 277 |
|
| 278 |
prog.py:1: error: Library stubs not installed for "yaml" |
| 279 |
prog.py:1: note: Hint: "python3 -m pip install types-PyYAML" |
| 280 |
prog.py:2: error: Library stubs not installed for "requests" |
| 281 |
prog.py:2: note: Hint: "python3 -m pip install types-requests" |
| 282 |
... |
| 283 |
|
| 284 |
In this case, you can provide mypy a different source of type information, |
| 285 |
by installing a *stub* package. A stub package is a package that contains |
| 286 |
type hints for another library, but no actual code. |
| 287 |
|
| 288 |
.. code-block:: shell |
| 289 |
|
| 290 |
$ python3 -m pip install types-PyYAML types-requests |
| 291 |
|
| 292 |
Stubs packages for a distribution are often named ``types-<distribution>``. |
| 293 |
Note that a distribution name may be different from the name of the package that |
| 294 |
you import. For example, ``types-PyYAML`` contains stubs for the ``yaml`` |
| 295 |
package. |
| 296 |
|
| 297 |
For more discussion on strategies for handling errors about libraries without |
| 298 |
type information, refer to :ref:`fix-missing-imports`. |
| 299 |
|
| 300 |
For more information about stubs, see :ref:`stub-files`. |
| 301 |
|
| 302 |
Next steps |
| 303 |
********** |
| 304 |
|
| 305 |
If you are in a hurry and don't want to read lots of documentation |
| 306 |
before getting started, here are some pointers to quick learning |
| 307 |
resources: |
| 308 |
|
| 309 |
* Read the :ref:`mypy cheatsheet <cheat-sheet-py3>`. |
| 310 |
|
| 311 |
* Read :ref:`existing-code` if you have a significant existing |
| 312 |
codebase without many type annotations. |
| 313 |
|
| 314 |
* Read the `blog post <https://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/>`_ |
| 315 |
about the Zulip project's experiences with adopting mypy. |
| 316 |
|
| 317 |
* If you prefer watching talks instead of reading, here are |
| 318 |
some ideas: |
| 319 |
|
| 320 |
* Carl Meyer: |
| 321 |
`Type Checked Python in the Real World <https://www.youtube.com/watch?v=pMgmKJyWKn8>`_ |
| 322 |
(PyCon 2018) |
| 323 |
|
| 324 |
* Greg Price: |
| 325 |
`Clearer Code at Scale: Static Types at Zulip and Dropbox <https://www.youtube.com/watch?v=0c46YHS3RY8>`_ |
| 326 |
(PyCon 2018) |
| 327 |
|
| 328 |
* Look at :ref:`solutions to common issues <common_issues>` with mypy if |
| 329 |
you encounter problems. |
| 330 |
|
| 331 |
* You can ask questions about mypy in the |
| 332 |
`mypy issue tracker <https://github.com/python/mypy/issues>`_ and |
| 333 |
typing `Gitter chat <https://gitter.im/python/typing>`_. |
| 334 |
|
| 335 |
* For general questions about Python typing, try posting at |
| 336 |
`typing discussions <https://github.com/python/typing/discussions>`_. |
| 337 |
|
| 338 |
You can also continue reading this document and skip sections that |
| 339 |
aren't relevant for you. You don't need to read sections in order. |