Sub topic 17
Running checks in CI and in your editor
This chapter assumes you can run mypy and pyright from the command line and that your settings are in pyproject.toml, as covered in the configuration chapters. It also assumes your project uses a virtual environment.
Two places, two jobs
The editor and continuous integration (CI) both run the checker, but they do different jobs.
- The editor gives feedback while you type, so you fix a mistake within seconds.
- CI is the gate. It runs the same checks on every pull request, so no one can merge code that fails them, whatever their local setup.
Setting up the editor
Most editors run a checker as a language server and underline errors as you type.
- In VS Code, the Pylance extension is built on Pyright. Microsoft also publishes a separate mypy extension.
- Editors such as Neovim and Helix can run Pyright's language server directly.
- Other editors, such as PyCharm, have their own built-in checker, so check which engine yours uses.
Whichever you pick, point the editor at your project's virtual environment. If it uses a different interpreter, it cannot find your installed packages. You then see "import could not be resolved" errors that the command line does not show.
Setting up CI
A CI job installs the project and its checkers, then runs them. Both tools exit with a non-zero status when they find errors, so CI marks the job as failed without any extra scripting. This GitHub Actions workflow runs both checkers:
name: typecheck
on:
pull_request:
push:
branches: [main]
jobs:
types:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python -m pip install -r requirements-dev.txt
- run: mypy
- run: pyrightRunning mypy and pyright with no arguments works because files and include in pyproject.toml already name the src directory. CI and your laptop therefore check the same code with the same settings.
Common errors
- Version drift. A new checker release can add errors to code that passed yesterday. Pin exact versions of
mypyandpyrightinrequirements-dev.txt, and upgrade them deliberately in their own pull request. - Missing dependencies. If CI does not install your project's libraries and their stub packages (such as
types-requests), the checkers report unresolved imports. Install the same development requirements that you use locally. - Different Python versions. Set
python_versionandpythonVersionin the configuration so results do not depend on the interpreter CI happens to use.
Exercise
Your editor shows no type errors, but CI fails with "Cannot find implementation or library stub for module named requests". What is the most likely cause, and how do you fix it?
Show answer
CI has not installed the stub package for the library, or the library itself, while your local environment has. Add types-requests (and the library) to the development requirements that CI installs. Then pin the versions so both environments match.