Creating a stub
Here is an overview of how to create a stub file:
Write a stub file for the library (or an arbitrary module) and store it asa
.pyi
file in the same directory as the library module.Alternatively, put your stubs (
.pyi
files) in a directoryreserved for stubs (e.g.,myproject/stubs
). In this case youhave to set the environment variableMYPYPATH
to refer to thedirectory. For example:
- $ export MYPYPATH=~/work/myproject/stubs
Use the normal Python file name conventions for modules, e.g. csv.pyi
for module csv
. Use a subdirectory with init.pyi
for packages. Notethat PEP 561 stub-only packages must be installed, and may not be pointedat through the MYPYPATH
(see PEP 561 support).
If a directory contains both a .py
and a .pyi
file for thesame module, the .pyi
file takes precedence. This way you caneasily add annotations for a module even if you don’t want to modifythe source code. This can be useful, for example, if you use 3rd partyopen source libraries in your program (and there are no stubs intypeshed yet).
That’s it! Now you can access the module in mypy programs and type checkcode that uses the library. If you write a stub for a library module,consider making it available for other programmers that use mypyby contributing it back to the typeshed repo.
There is more information about creating stubs in themypy wiki.The following sections explain the kinds of type annotations you can usein your programs and stub files.
Note
You may be tempted to point MYPYPATH
to the standard library orto the site-packages
directory where your 3rd party packagesare installed. This is almost always a bad idea – you will likelyget tons of error messages about code you didn’t write and thatmypy can’t analyze all that well yet, and in the worst casescenario mypy may crash due to some construct in a 3rd partypackage that it didn’t expect.