>_ DevTrendsen

Language

Home

Languages

Sections

Frontend Backend Mobile DevOps AI / ML GameDev Blockchain Embedded Security
Python

How Mypy Makes Python Code More Reliable and Why You Should Adopt It Today

mypy logo

Imagine a classic scenario. You deploy a feature before the weekend, all tests pass, and five minutes after deployment your monitoring goes haywire. The logs show a familiar TypeError: unsupported operand type(s) for +: 'int' and 'str'. Someone passed a string from a web form instead of a number, the function tried to add values together, and the service went down.

Python's dynamic typing gives you a great start and lets you quickly build prototypes. However, as the project grows, it becomes a constant source of risk. Any refactoring of an old module turns into a minefield.

This is where mypy helps — the official static type checker for Python that catches such errors before the code even runs.

The Idea Behind Gradual Typing

Type annotations appeared in Python with the release of PEP 484 in 2015. Mypy reads these annotations and validates their logic, without affecting program execution in any way. To the Python interpreter itself, your types remain just hints in the code, similar to regular comments.

The developers built gradual typing into the tool. You don't have to rewrite the entire codebase overnight. You can annotate a couple of critical modules, such as a payment gateway or authorization, and leave the rest of the code dynamic.

Let's look at a simple error example:

def calculate_discount(price: float, discount: float) -> float:
    return price * (1 - discount)

user_input = input("Введите размер скидки: ")
total = calculate_discount(100.0, user_input)

If you run the check from the terminal:

mypy script.py

The analyzer immediately shows the location of the error:

script.py:5: error: Argument 2 to "calculate_discount" has incompatible type "str"; expected "float"

You caught a potential production crash right during development, spending exactly one second.

Main Features of the Analyzer

The tool can do much more than just compare basic numbers and strings. Mypy understands complex code structure thanks to a thoughtful type system:

  • Automatic type inference. If you write items = [1, 2, 3], the tool will figure out on its own that it's a list of integers.
  • Support for generics, tuples, functions, and type matching.
  • Structural subtyping through Protocols and Union types.
  • Control of None values. Say goodbye to unexpected AttributeError: 'NoneType' object has no attribute.

When a project grows to hundreds of thousands of lines, a regular check starts taking time. For such situations, the authors created a daemon mode:

dmypy run -- script.py

The daemon stays in memory, stores the dependency graph, and when files change, it recalculates only the difference. The response comes instantly.

What Makes mypy Fast

An interesting detail about the repository: mypy is written in Python but can compile itself.

The authors created the mypyc utility, which translates typed Python code into C extensions. Thanks to this compilation, the analyzer itself runs about four times faster than the standard interpreter.

Integrating Into Your Workflow

Manually checking code through the console is inconvenient. Mypy integrates easily with everyday tools.

Installation takes one command:

python3 -m pip install -U mypy

There are ready-made plugins for VS Code, PyCharm, Vim, and Emacs. Errors are highlighted right in the editor as you type. By setting up integration with pre-commit, you'll block the ability to commit code with incorrect types.

Where Difficulties Arise

The type checker doesn't solve absolutely every problem. You'll have to live with some inconveniences.

Third-party libraries don't always ship with annotations. For popular packages, there's a separate repository typeshed, but for an obscure library, you'll either have to write .pyi files yourself or silence the checks with # type: ignore.

Additionally, the project repository has over three thousand open issues. Edge cases of complex metaprogramming sometimes lead to false positives.

Who the Tool Is For

For a one-off 50-line script, mypy is clearly overkill. Annotations would just waste your time.

But if you're building a long-running project with FastAPI, Django, or developing a service that a team works on, mypy will protect your code from trivial typos and logic bugs.

Start with a small step: install the package, set up a lenient configuration file mypy.ini, and add annotations to a couple of complex functions. The code will become clearer without reading lengthy documentation.

Related projects