mypy python что это

Getting startedВ¶

This chapter introduces some core concepts of mypy, including function annotations, the typing module, library stubs, and more.

Be sure to read this chapter carefully, as the rest of the documentation may not make much sense otherwise.

Installing and running mypyВ¶

Mypy requires Python 3.6 or later to run. Once you’ve installed Python 3, install mypy using pip:

Once mypy is installed, run it by using the mypy tool:

This command makes mypy type check your program.py file and print out any errors it finds. Mypy will type check your code statically: this means that it will check for errors without ever running your code, just like a linter.

This means that you are always free to ignore the errors mypy reports and treat them as just warnings, if you so wish: mypy runs independently from Python itself.

However, if you try directly running mypy on your existing Python code, it will most likely report little to no errors: you must add type annotations to your code to take full advantage of mypy. See the section below for details.

Function signatures and dynamic vs static typingВ¶

A function without type annotations is considered to be dynamically typed by mypy:

By default, mypy will not type check dynamically typed functions. This means that with a few exceptions, mypy will not report any errors with regular unannotated Python.

This is the case even if you misuse the function: for example, mypy would currently not report any errors if you tried running greeting(3) or greeting(b»Alice») even though those function calls would result in errors at runtime.

You can teach mypy to detect these kinds of bugs by adding type annotations (also known as type hints). For example, you can teach mypy that greeting both accepts and returns a string like so:

This function is now statically typed: mypy can use the provided type hints to detect incorrect usages of the greeting function. For example, it will reject the following calls since the arguments have invalid types:

Note that this is all still valid Python 3 code! The function annotation syntax shown above was added to Python as a part of Python 3.0.

If you are trying to type check Python 2 code, you can add type hints using a comment-based syntax instead of the Python 3 annotation syntax. See our section on typing Python 2 code for more details.

Being able to pick whether you want a function to be dynamically or statically typed can be very helpful. For example, if you are migrating an existing Python codebase to use static types, it’s usually easier to migrate by incrementally adding type hints to your code rather than adding them all at once. Similarly, when you are prototyping a new feature, it may be convenient to initially implement the code using dynamic typing and only add type hints later once the code is more stable.

The earlier stages of analysis performed by mypy may report errors even for dynamically typed functions. However, you should not rely on this, as this may change in the future.

More function signaturesВ¶

Here are a few more examples of adding type hints to function signatures.

Make sure to remember to include None : if you don’t, the function will be dynamically typed. For example:

Arguments with default values can be annotated like so:

*args and **kwargs arguments can be annotated like so:

Additional types, and the typing moduleВ¶

For example, to indicate that some function can accept a list of strings, use the list[str] type (Python 3.9 and later):

In Python 3.8 and earlier, you can instead import the List type from the typing module:

You can find many of these more complex static types in the typing module.

In the above examples, the type signature is perhaps a little too rigid. After all, there’s no reason why this function must accept specifically a list – it would run just fine if you were to pass in a tuple, a set, or any other custom iterable.

You can express this idea using the collections.abc.Iterable type instead of List (or typing.Iterable in Python 3.8 and earlier):

As another example, suppose you want to write a function that can accept either ints or strings, but no other types. You can express this using the Union type:

When adding types, the convention is to import types using the form from typing import Union (as opposed to doing just import typing or import typing as t or from typing import * ).

For brevity, we often omit imports from typing or collections.abc in code examples, but mypy will give an error if you use types such as Iterable without first importing them.

Local type inferenceВ¶

Once you have added type hints to a function (i.e. made it statically typed), mypy will automatically type check that function’s body. While doing so, mypy will try and infer as many details as possible.

We saw an example of this in the normalize_id function above – mypy understands basic isinstance checks and so can infer that the user_id variable was of type int in the if-branch and of type str in the else-branch. Similarly, mypy was able to understand that name could not possibly be None in the greeting function above, based both on the name is None check and the variable assignment in that if statement.

As another example, consider the following function. Mypy can type check this function without a problem: it will use the available context and deduce that output must be of type List[float] and that num must be of type float :

Mypy will warn you if it is unable to determine the type of some variable – for example, when assigning an empty dictionary to some global value:

You can teach mypy what type my_global_dict is meant to have by giving it a type hint. For example, if you knew this variable is supposed to be a dict of ints to floats, you could annotate it using either variable annotations (introduced in Python 3.6 by PEP 526) or using a comment-based syntax like so:

Library stubs and typeshedВ¶

Mypy uses library stubs to type check code interacting with library modules, including the Python standard library. A library stub defines a skeleton of the public interface of the library, including classes, variables and functions, and their types. Mypy ships with stubs for the standard library from the typeshed project, which contains library stubs for the Python builtins, the standard library, and selected third-party packages.

For example, consider this code:

Without a library stub, mypy would have no way of inferring the type of x and checking that the argument to chr() has a valid type.

Mypy complains if it can’t find a stub (or a real module) for a library module that you import. Some modules ship with stubs or inline annotations that mypy can automatically find, or you can install additional stubs using pip (see Missing imports and Using installed packages for the details). For example, you can install the stubs for the requests package like this:

Starting in mypy 0.900, most third-party package stubs must be installed explicitly. This decouples mypy and stub versioning, allowing stubs to updated without updating mypy. This also allows stubs not originally included with mypy to be installed. Earlier mypy versions included a fixed set of stubs for third-party packages.

Configuring mypyВ¶

Mypy supports many command line options that you can use to tweak how mypy behaves: see The mypy command line for more details.

This flag is mostly useful if you’re starting a new project from scratch and want to maintain a high degree of type safety from day one. However, this flag will probably be too aggressive if you either plan on using many untyped third party libraries or are trying to add static types to a large, existing codebase. See Using mypy with an existing codebase for more suggestions on how to handle the latter case.

Next stepsВ¶

If you are in a hurry and don’t want to read lots of documentation before getting started, here are some pointers to quick learning resources:

Read Using mypy with an existing codebase if you have a significant existing codebase without many type annotations.

Read the blog post about the Zulip project’s experiences with adopting mypy.

If you prefer watching talks instead of reading, here are some ideas:

Look at solutions to common issues with mypy if you encounter problems.

You can ask questions about mypy in the mypy issue tracker and typing Gitter chat.

You can also continue reading this document and skip sections that aren’t relevant for you. You don’t need to read sections in order.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *