Skip to content
Latchkey

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

Terminal
MYPYPATH=src mypy --explicit-package-bases --namespace-packages src/
# config form
# [tool.mypy]
# explicit_package_bases = true
# mypy_path = "src"

Options

Flag or keyWhat it does
--explicit-package-basesUse MYPYPATH roots as package bases, do not guess
explicit_package_basesConfig key form (true/false)
mypy_path / MYPYPATHRoots from which module names are computed
--namespace-packagesUsually 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.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →