Ever heard the term “type checking” in Python scripts? If not, let’s make your day. Welcome to our comprehensive tutorial series on ‘mypy’, an optional static type checker for Python.
Table of contents
What is Mypy?
Mypy is a powerful tool that allows developers to utilize the concept of static typing in their Python programming journey. If you’re coming from a statically typed language like C or Java, you will remember having to declare variable types. Python, as a dynamically typed language, doesn’t require this. But with mypy, we can selectively add these type declarations to our Python data, enabling an additional layer of code reliability and robustness.
Primarily, mypy helps in reducing the odds of runtime errors in Python codes, which are normally caught during the execution of the script. Mypy does so even before the code runs, i.e., during the code-writing phase itself. This ‘compile-time’ error detection often leads to more reliable code, saving not only a headache but potentially hours of debug time later.
Python’s dynamic nature is both its strength and weakness, depending on how one uses it. Mypy offers the ‘best of both worlds’, combining Python’s dynamic typing with the benefits of static type checking. Moreover, it can improve code-readability as well. Thus, learning and mastering mypy gives you an edge in writing more robust, reliable, and efficient Python scripts.
How to get started with Mypy
Firstly, mypy is an external tool that is not shipped with your default Python installation, so you’ll need to install it manually. Open your terminal and type the following pip command:
pip install mypy
With mypy installed, let’s dive into some examples:
Writing Python with type hints
Just like you would in a statically-typed language such as Java, you start by declaring the types of your variables, functions, and methods.
Here’s a simple Python program with type hints:
def greet(name: str) -> str:
return 'Hello, ' + name
print(greet('World'))The ‘:str’ in the function greet indicates that the ‘name’ argument should be of type string. With ‘->str’ we’re specifying that the function will return a string.
Using Mypy to check your Python scripts
After writing a script with type hints, use the mypy tool from command line to check your file. If your filename is ‘script.py’, you’d type:
mypy script.py
If everything is correctly typed, mypy will not return any information. This means your script is good to go! If there are issues, mypy will tell you exactly where and what the problem is.
A few more examples
Let’s look at some examples that will cause a type hint violation:
def double(number: int) -> int:
return number * 2
double('string') # this will cause a type hint violation
def add(number1: int, number2: int) -> int:
return number1 + number2
add(5, 'string') # this will cause a type hint violationMypy can also work with custom classes. Take a look at this:
class MyNumber:
def __init__(self, number: int):
self.number = number
def add(number1: MyNumber, number2: MyNumber) -> MyNumber:
return MyNumber(number1.number + number2.number)
number1 = MyNumber(5)
number2 = MyNumber(10)
print(add(number1, number2).number) # this will work correctly
print(add(number1, 'string').number) # this will cause a type hint violationAbove, we have created our own class and used it in our type hinting. This allows us to gain the benefits of type hinting even with our custom objects.
Applying Mypy in Common Scenarios
As developers, we often find ourselves in common situations requiring specific pieces of code. Let’s see how mypy can be used in some such instances.
Using Mypy with Lists
Mypy allows the application of type hinting to lists as well. Here is how you use type hinting with lists:
from typing import List
def addAll(numbers: List[int]) -> int:
return sum(numbers)
print(addAll([1, 2, 3, 4, 5])) # this is okay
print(addAll([1, 2, "3", 4, 5])) # this will cause a violationType Hinting with Dictionaries
Just as with lists, we can also apply type hinting to dictionaries:
from typing import Dict
def printAll(student: Dict[str, str]) -> None:
for key, value in student.items():
print(key, value)
student = {
"name": "John",
"class": "IV",
"roll_id": "42"
}
printAll(student) # this is okayMypy with Optional Types
There can be instances where variables can take a value of None. This situation calls for the use of Optional types:
from typing import Optional
def greet(name: Optional[str] = None) -> str:
if name is not None:
return "Hello, " + name
else:
return "Hello, Guest"
print(greet()) # this is okay
print(greet("John Doe")) # this is okay tooBy declaring the type as Optional[str], we’re telling mypy that “name” can either be a string or None.
Parameters with Default Values
If your function parameters have default values, you can still add type hints to them:
def greet(name="World") -> str:
return "Hello, " + name
print(greet()) # This is okay
print(greet("John Doe")) # This is okay tooHere, even though a default value has been provided for the “name” parameter, mypy will still enforce the type checking.
Where to go next
Well done! You’re on your way to mastering mypy, thereby enhancing the robustness and readability of your Python programs. Step up your journey with Python by delving deeper into other concepts. Remain curious, continue asking questions, and never stop learning!
An exemplary next step would be the Python Mini-Degree we offer at Zenva Academy. Our Python Mini-Degree provides a learner-friendly approach to Python. It’s an ideal combination of Python basics, object-oriented programming, algorithms, game development, and app creation. With interactive modules, in-course quizzes, and live coding lessons, this program is designed to cater to beginners just stepping into the programming world, as well as experienced developers looking to sharpen and enhance their skills.
If you wish to explore beyond our Python Mini-Degree or are looking for something more specific, browse through our expansive collection of other Python courses. From the fundamentals to more advanced topics, we’ve got you covered in every step of your learning journey.
At Zenva, we offer flexibility, up-to-date content, and certification. Our courses are tailor-made to fit your schedule, and we keep our material up to date to make sure you are learning the most relevant techniques. With Zenva, you can develop your skills and advance your career, going from beginner to professional.
Conclusion
We are truly excited about your decision to step into the world of Python and enhance your prowess with mypy. We believe that it will add significant value to your programming journey by allowing you to develop readable, reliable, and robust Python scripts.
Embrace the power of mypy and continue your pursuit of knowledge and skill acquisition with us, here at Zenva. Stand out from the programming crowd and level up your resume with our comprehensive Python Mini-Degree or any of our specialized Python courses. Happy coding!
Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.







