Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Type Checking With Mypy

Give Feedback

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

Chris Bailey RP Team on Oct. 31, 2019

Hi Charlie, I’m using VScode as my primary Python tool currently. I will ask others on the team if they have experience with the Mypy plugin. Looking it over it seems like it might make the testing/type checking work flow easier, somewhat automated. I will get back to you when I hear more from the Real Python team. Thanks

charliem22 on Oct. 31, 2019

Thanks Chris. I’ll be interested in the results of your ‘survey.’ charlie

Pygator on Nov. 3, 2019

I wonder why the : is to the left of the args, but to the right of the return type?

Geir Arne Hjelle RP Team on Nov. 3, 2019

Ah … I hadn’t thought of that :)

You’re talking about something like this, right?

def headline(text: str) -> str:
                 ^            ^
            : to left    : to right

I guess the explanation is that the last : (after the return type) actually has nothing to do with the type annotation. The return type is “signaled” by the arrow ->. The final : is the usual : signaling the start of a block that you always need after a def ...

Chris Bailey RP Team on Nov. 4, 2019

Hi Charlie, I didn’t find many Pycharm users on the team, and if they were (and used Mypy) they used it stand alone. Also had another that uses Pycharm but mainly working in Python 2.7. Sorry I couldn’t provide more background on the plugin.

Pygator on Nov. 12, 2019

Thanks Geir

Become a Member to join the conversation.