Python Type Hints - How to Debug Types With reveal_type()2021-05-14
When working with type hints, it’s often useful to debug the types of variables.
Type checkers allow you to do this with
For example, take this code:
We don’t need to add a hint to
items since our type checker can infer its type.
But we might not be sure what type has been inferred—is it
list[int | None], the less useful
list[object], or worst
We can check by adding a call to
Then when we run our type checker, in this case Mypy, it will log the type of
Here Mypy wrote its “long-form spelling” of
list[int | None] (in a future version it may use a shorter form).
reveal_type() does not exist at runtime, so if we run our code with the call in place, Python crashes with a
So, we need to remove all calls to
reveal_type() before running our code.
A good way to make sure you never accidentally commit a call to
reveal_type() is to use flake8, perhaps under pre-commit.
It will flag calls with the error
F821 undefined name 'reveal_type'.
Mypy also supports
reveal_locals(), which does a
reveal_type() for each local variable.
This can save time when debugging several variables.
For example, if we take this code:
We can run Mypy and see:
The local variables
items have their types revealed, but the global variable
CONSTANT does not.
Want better tests? Check out my book Speed Up Your Django Tests which teaches you to write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- Python Type Hints - How to Narrow Types with isinstance(), assert, and Literal
- Python Type Hints - How to Fix Circular Imports
- Python Type Hints - Use object instead of Any
- Python Type Hints - How to Specify a Class Rather Than an Instance Thereof
Tags: mypy, python
© 2021 All rights reserved.