Question
How to make stub .pyi file automatically from an existing .py source file?
Answer
Use stubgen, which is included with mypy, to automatically generate draft .pyi files from existing Python source files.
Note: The generated
.pyifile should be reviewed manually. Automatically generated stubs may contain incomplete types orAnywhere the tool cannot infer accurate type information.
1. Install mypy
Run the following command:
python -m pip install mypy
2. Generate a Stub File from a Single Python File
Use the following command:
stubgen path/to/example.py -o stubs
Example:
stubgen calculator.py -o stubs
Expected output:
stubs/calculator.pyi
3. Generate Stubs for Multiple Python Files
stubgen foo.py bar.py -o stubs
This generates:
stubs/foo.pyi
stubs/bar.pyi
Alternatively, installing the module via pip install . allows PyCharm to generate skeletons automatically, which eliminates the need for maintaining a stub file.
For further context, note that this behavior is a known limitation of PyCharm. You can track its progression or vote for its prioritization here: Build skeletons for binary modules under project content.
Comments
0 comments
Please sign in to leave a comment.