Adding type hints to OpenStack (starting with Oslo)
Cyril Roelandt
cyril at redhat.com
Sat Jan 26 04:26:15 UTC 2019
Hello,
I have recently been looking at mypy[1], a static type checker for
Python. It uses optional type hints[2] to perform type checking. Using
mypy has many benefits:
- it allows developers to find type-related bugs that could cause a
program to crash or display an unexpected behaviour at runtime;
- it replaces type information that is usually given in docstrings, and
may be outdated;
- mypy runs can be integrated into a CI, making sure there are no
regressions;
- mypy works with both Python 2 and 3;
- adding type information may be done incrementally;
- library developers may expose type information, helping their users.
Type information is available for most of the standard Python library,
and for the most popular libraries on PyPI, through typeshed[3]. It is
therefore possible to write bad code such as:
$ cat test.py
import requests
requests.get(123)
And have mypy warn us that something is wrong:
$ mypy test.py
test.py:2: error: Argument 1 has incompatible type "int"; expected "Union[str, bytes]"
I would like to add type hints to OpenStack, starting with a small
project (because it would probably be quick and easy) that is used by a
lot of other OpenStack projects (because they would benefit from the
type hints as well). Oslo seems like a reasonable choice.
I took the liberty of implementing a proof of concept on top of
oslo.config[4]. Using this branch, you should be able to:
1) Run "tox -etype" to run mypy on the whole code base
2) Write a badly typed program such as this one:
$ cat test.py
from oslo_config import cfg
common_opts = [
cfg.IntOpt('test', min='3'),
cfg.HostAddressOpt('host', version='4'),
]
And have mypy show you the type errors:
$ mypy test.py
test.py:4: error: Argument "min" to "IntOpt" has incompatible type "str"; expected "Optional[int]"
test.py:5: error: Argument "version" to "HostAddressOpt" has incompatible type "str"; expected "Optional[int]"
Does anyone know about mypy? Would anyone be interested in seeing type hints
added to OpenStack?
Looking forward to hearing your thoughts,
Cyril
[1] http://mypy-lang.org/
[2] https://www.python.org/dev/peps/pep-0484/
[3] https://github.com/python/typeshed
[4] https://github.com/CyrilRoelandteNovance/oslo.config/tree/type
More information about the openstack-discuss
mailing list