Today I learnt about Python type hints š
Up until today I knew type hints existed in Python and had read code which used them but hadnāt written any. I wanted to decide if this is a useful technique for me. Letās say I have the following function:
I like the idea that I could automatically detect if someone calls it with parameters which arenāt numbers. I wrote a few different calls to test how the function behaves.
Hereās a type hint version of the same code:
I was hoping the Python interpreter would throw an exception if I call:
It doesnāt, so whilst type hints are useful for documenting what type of parameters should be used, and the return type, on their own type hints wonāt help catch errors.
Mypy
To get the behaviour I wanted I needed to install Mypy:
Then by running:
I got the following output:
Very good! However interestingly Mypy is ok with:
So itās happy with treating True
as 1
which surprised me.
Python Number Type
My function calculates the product of two numbers, so Iād expect the following to be a valid call:
However I specified the parameter types to be int
so this isnāt valid and Mypy tells me off! Thereās no ānumber typeā in Python but PEP 484 states if we set the type to be float
then an argument of type int
is acceptable. So our function now looks like:
Conclusion
On the one hand I like Python type hints as they are adding extra detail to the code conveying how it should be used. It also feels similar to typing in Swift which Iām a fan of. On the other hand the fact the Python interpreter ignores the type hints and youāre required to run checks separately with MyPy makes this feel a bit more of a faff, also I found Mypy a bit slow to run so maybe this would work best as a CI step.