Adding type hints to OpenStack (starting with Oslo)

Doug Hellmann doug at doughellmann.com
Sat Jan 26 14:02:53 UTC 2019


Cyril Roelandt <cyril at redhat.com> writes:

> 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.
>
> 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
>

We're still required to support python 2 through the beginning of the U
cycle [5]. Is it possible to apply the type hints in a way that allows
us to maintain that support?

[5] https://governance.openstack.org/tc/resolutions/20180529-python2-deprecation-timeline.html

-- 
Doug



More information about the openstack-discuss mailing list