
Tighten up your code and identify errors before they occur with
mypy
.
I've been using dynamic languages—Perl, Ruby and Python—for many years. I love the flexibility and expressiveness that such languages provide. For example, I can define a function that sums numbers:
def mysum(numbers):
total = 0
for one_number in numbers:
total += one_number
return total
The above function will work on any iterable that returns numbers. So I can run the above on a list, tuple or set of numbers. I can even run it on a dictionary whose keys are all numbers. Pretty great, right?
Yes, but for my students who are used to static, compiled languages, this is a very hard thing to get used to. After all, how can you make sure that no one passes you a string, or a number of strings? What if you get a list in which some, but not all, of the elements are numeric?
For a number of years, I used to dismiss such worries. After all, dynamic languages have been around for a long time, and they have done a good job. And really, if people are having these sorts of type mismatch errors, then maybe they should be paying closer attention. Plus, if you have enough testing, you'll probably be fine.
But as Python (and other dynamic languages) have been making inroads into large companies, I've become increasingly convinced that there's something to be said for type checking. In particular, the fact that many newcomers to Python are working on large projects, in which many parts need to interoperate, has made it clear to me that some sort of type checking can be useful.
How can you balance these needs? That is, how can you enjoy Python as a dynamically typed language, while simultaneously getting some added sense of static-typing stability?
One of the most popular answers is a system known as mypy
, which
takes advantage of Python 3's type annotations for its own purposes.
Using mypy
means that you can write and run Python in the normal way,
gradually adding static type checking over time and checking it
outside your program's execution.
In this article, I start exploring mypy
and how you can use it to
check for problems in your programs. I've been impressed by
mypy
,
and I believe you're likely to see it deployed in a growing number
of places, in no small part because it's optional, and thus allows
developers to use it to whatever degree they deem necessary,
tightening things up over time, as well.
Dynamic and Strong Typing
In Python, users enjoy not only dynamic typing, but also strong typing. "Dynamic" means that variables don't have types, but that values do. So you can say: