Python recently had a big development around static typing. Starting with Python 3.5, type hints are a thing. That’s what PEP 0484 was all about. The type hinting syntax is completely based on the function annotation syntax that was introduced way earlier with PEP 3107. This allowed PEP 0484 to be a change that did not involve new syntax which makes it very attractive and easy to adapt.
So, how does that work? The syntax is actually pretty intuitive for simple cases. For example:
def greeting(name: str) -> str:
return 'Hello ' + name
The type hinting system does support very complicated things too though. You can also use user types, callables, multiple overloads using unions, even generic types. You can see a lot of examples in the PEP itself.
You can also watch Guido van Rossum’s talk about type hinting at the last PyCon, it’s really interesting and covers a lot of details.
Finally, with all these type hints, what do we do with them? Well, there is this great library that has been existing for a while, well before Python 3.5 and PEP 0484. Actually, the type hinting syntax officially introduced now is based on that library but just formalized. The library is called mypy and is basically a static type checker for Python. When installed, you can use the mypy
executable to type check any Python script that contains type annotations.
For example, let’s put above function definition in a file, and call it with the wrong type arguments:
greeting(123)
Running mypy on the file, gives the following output:
$ mypy test.py
test.py:4: error: Argument 1 to "greeting" has incompatible type "int"; expected "str"
mypy, while technically experimental, is a very powerful tool that works really well. If you’re into this thing and would adopt type annotations, then you should really check it out.