Automatic stub generation (stubgen)
A stub file (see PEP 484) contains only type hints for the publicinterface of a module, with empty function bodies. Mypy can use a stubfile instead of the real implementation to provide type informationfor the module. They are useful for third-party modules whose authorshave not yet added type hints (and when no stubs are available intypeshed) and C extension modules (which mypy can’t directly process).
Mypy includes the stubgen
tool that can automatically generatestub files (.pyi
files) for Python modules and C extension modules.For example, consider this source file:
- from other_module import dynamic
- BORDER_WIDTH = 15
- class Window:
- parent = dynamic()
- def __init__(self, width, height):
- self.width = width
- self.height = height
- def create_empty() -> Window:
- return Window(0, 0)
Stubgen can generate this stub file based on the above file:
- from typing import Any
- BORDER_WIDTH: int = ...
- class Window:
- parent: Any = ...
- width: Any = ...
- height: Any = ...
- def __init__(self, width, height) -> None: ...
- def create_empty() -> Window: ...
Stubgen generates draft stubs. The auto-generated stub files oftenrequire some manual updates, and most types will default to Any
.The stubs will be much more useful if you add more precise type annotations,at least for the most commonly used functionality.
The rest of this section documents the command line interface of stubgen.Run stubgen —help
for a quick summary of options.
Note
The command-line flags may change between releases.