In this lesson, you’ll explore how to use Mypy to do type checking on your Python code. Mypy is the most common tool for doing type checking:
Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or “duck”) typing and static typing. (Source)
Mypy was started by Jukka Lehtosalo during his Ph.D. studies at Cambridge around 2012. Initially, Mypy started as a standalone variant of Python with seamless dynamic and static typing. See Jukka’s slides from PyCon Finland 2012 for examples of the original vision of Mypy.
Following a suggestion by Guido van Rossum, Mypy was rewritten to use annotations instead, making it a static type checker for regular Python code.
If you don’t have Mypy on your system, you can install it using pip:
$ pip install mypy
Put the following code in a file called headlines.py
:
# headlines.py
def headline(text: str, align: bool = True) -> str:
if align:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "o")
print(headline("python type checking"))
print(headline("use mypy", align="center"))
This is essentially the same code you saw earlier: the definition of headline()
and two examples that are using it.
Now run Mypy on this code:
$ mypy headlines.py
headlines.py:10: error: Argument "align" to "headline" has incompatible
type "str"; expected "bool"
Based on the type hints, Mypy is able to tell you that you are using the wrong type on line 10. To fix the issue in the code, you should change the value of the align
argument you are passing in. You might also rename the align flag to something less confusing:
# headlines.py
def headline(text: str, centered: bool = False):
if not centered:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "o")
print(headline("python type checking"))
print(headline("use mypy", centered=True))
Here you changed align
to centered and correctly used a Boolean value for centered
when calling headline()
. The code now passes Mypy:
$ mypy headlines.py
$
No output from Mypy means that no type errors were detected. Furthermore, when you run the code you see the expected output:
$ python headlines.py
Python Type Checking
--------------------
oooooooooooooooooooo Use Mypy oooooooooooooooooooo
The first headline is aligned to the left, while the second one is centered.
charliem22 on Oct. 30, 2019
Hi Chris – I use PyCharm Professional and I’m wondering if there is any advantage to adding the Mypy plugin to my PyCharm environment. I searched a bit online and couldn’t find an obvious ‘value-added’ advantage. What’s your opinion/experience?
Thanks in advance, charlie