mypy --explicit-package-bases: Fix Module Names
mypy --explicit-package-bases controls how mypy maps a file path to a fully-qualified module name.
When mypy guesses the wrong package root, the same file can be seen under two module names. This flag, with MYPYPATH, makes the mapping explicit.
What it does
mypy --explicit-package-bases tells mypy not to guess the package base by walking up looking for __init__.py, and instead to treat the roots in MYPYPATH (and the current directory) as package bases. This makes a file map to exactly one module name.
Common usage
MYPYPATH=src mypy --explicit-package-bases --namespace-packages src/
# config form
# [tool.mypy]
# explicit_package_bases = true
# mypy_path = "src"Options
| Flag or key | What it does |
|---|---|
| --explicit-package-bases | Use MYPYPATH roots as package bases, do not guess |
| explicit_package_bases | Config key form (true/false) |
| mypy_path / MYPYPATH | Roots from which module names are computed |
| --namespace-packages | Usually enabled together for src layouts |
In CI
For a src/ layout, set mypy_path = "src" (or MYPYPATH=src) and explicit_package_bases = true. This is the canonical fix for the duplicate-module error and keeps module names stable so the .mypy_cache stays valid across runs.
Common errors in CI
The error this targets is "error: Source file found twice under different module names: 'pkg.mod' and 'src.pkg.mod'". It means mypy computed two module paths for one file. Set explicit_package_bases plus mypy_path/MYPYPATH so the base is fixed and the file resolves to a single name.