How imports are found
When mypy encounters an import
statement or receives modulenames from the command line via the —module
or —package
flags, mypy tries to find the module on the file system similarto the way Python finds it. However, there are some differences.
First, mypy has its own search path.This is computed from the following items:
- The
MYPYPATH
environment variable(a colon-separated list of directories). - The
mypy_path
config file option. - The directories containing the sources given on the command line(see below).
- The installed packages marked as safe for type checking (seePEP 561 support)
- The relevant directories of thetypeshed repo.
Note
You cannot point to a PEP 561 package via the MYPYPATH
, it must beinstalled (see PEP 561 support)
For sources given on the command line, the path is adjusted by crawlingup from the given file or package to the nearest directory that does notcontain an init.py
or init.pyi
file. If the given pathis relative, it will only crawl as far as the current working directory.
Second, mypy searches for stub files in addition to regular Python filesand packages.The rules for searching for a module foo
are as follows:
- The search looks in each of the directories in the search path(see above) until a match is found.
- If a package named
foo
is found (i.e. a directoryfoo
containing aninit.py
orinit.pyi
file)that’s a match. - If a stub file named
foo.pyi
is found, that’s a match. - If a Python module named
foo.py
is found, that’s a match.
These matches are tried in order, so that if multiple matches are foundin the same directory on the search path(e.g. a package and a Python file, or a stub file and a Python file)the first one in the above list wins.
In particular, if a Python file and a stub file are both present in thesame directory on the search path, only the stub file is used.(However, if the files are in different directories, the one foundin the earlier directory is used.)