Disclaimer: I wrote this to crystalize my own learning. I don't claim to be an expert.
A brief introduction to MyPy.
Contents:
- Why bother with MyPy.
- Two example scripts.
- Two exercise scripts.
Python is dynamically typed, but sometimes this can make life harder.
Debugging is easy in this trivial example, but in a bigger codebase adding typechecking to this function would reduce risk of accidentally calling it with args of the wrong type:
def get_reachable_hosts(allhosts, badhosts):
"""Do something for every host that you can
reach from a list of hosts.
"""
goodhosts = allhosts - badhosts
for goodhost in goodhosts:
... # do stuff
get_reachable_hosts(['foo', 'bar', 'baz'], set('foo'))
Classic example is:
def greet(name):
print(f'Hello {name}')
greet({42: 'Deep thought'})
# Python handles this
# even if it's not sensible.
>>> Hello {42: 'Deep thought'}
Docstring relies on human proofing for being up to date.
def function_has_evolved(input_):
"""Do something to a string.
Args (str): Do something to a string
"""
return [func(i) for i in input_]
Ultimately though, MyPy is optional. You can have both static and dynamic typing for different bits of the same script!
Either:
- Use this link to download and unzip in a location of your choice.
- On the command line:
git clone https://github.com/wxtim/learn-mypy.git
. Thencd learn-mypy
.