Background
In lldb, we have a minimum python version of 3.8, if python support is enabled.
Since python 3.5 it has been possible to add type annotations to code and the new ‘typing’ module was introduced.
I have been working on improving the unit tests for lldb-dap and while working on that, I found its helpful to have additional type information. This can help in the IDE by helping me ensure the value or structure or parameters of a function are correct. Here is an example PR of the kinds of type annotations I have been adding.
However by default the type annotations are not going to do much (if anything).
In python, you need to run a static type checker to validate the types. There is some support for runtime type assertions using typing.assert_type, (EDIT: assert_type has no runtime side effects, its only a hint to the type checker) otherwise you need to invoke a tool like mypy or pyright. Other type checkers exist, but I believe those are the two most popular choices.
Proposal
At the moment, any python code annotated with types is not validated as part of the CI. This means that the types could regress over time.
We could address this in a few ways:
- Add a pre-commit hook to run the type checker, like the linter checks
- Add a pre-merge hook to run the type checker, like the linter checks
- Run the type checker before we run the python based tests
Additionally, if we wanted to run a type checker, we would also need to pick which type checker we’d like to use. Like I mentioned previously, mypy
and pyright
are two popular choices but others exist.
I think mypy
is a good option because its supported by the python core team and is a fairly common choice.
I also think it would be worth adding the type_extensions
library to the lldb/test/requirements.txt
since it includes back ports of new types for older versions of python.
Running mypy
At the moment, we don’t have a config setup specifically for running a type checker, but you can run the files directly like:
$ time mypy --python-version 3.8 \
lldb/packages/Python/lldbsuite/**/*.py \
lldb/test/API/tools/lldb-dap/**/*.py
... a couple of warnings / errors from existing code
mypy --python-version 3.8 lldb/packages/Python/lldbsuite/**/*.py 0.66s user 0.18s system 66% cpu 1.270 total
On my machine, an M1 Max MBP, it takes ~1.5s to run the type checker on the lldb unit tests.
Issue tracker link: [lldb] Add a CI step to run a python type checker · Issue #141877 · llvm/llvm-project · GitHub