Skip to content

Commit 6d3afa1

Browse files
committed
python typing / add stub files
1 parent 67a9b12 commit 6d3afa1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

docs/posts/2025/2025-02-01-python-type-hints.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,33 @@ def maybe_direction(x: str) -> None:
478478
print(f"{x} is not a cardinal direction")
479479
```
480480

481+
## Stub files
482+
483+
Python [standard library](https://docs.python.org/3/library/index.html) ships its type hints in the [typeshed repo](https://github.com/python/typeshed) with `.pyi` extension.
484+
485+
For third party libraries, you can save stub files along with your code in the same directory, or you can put them in a for e.g. `myproject/stubs` directory, and point it by the env var export `MYPYPATH=~/work/myproject/stubs`.
486+
487+
If a directory contains both a `.py` and a `.pyi` file for the same module, the `.pyi` file takes precedence. This way you can easily add annotations for a module even if you don’t want to modify the source code. This can help you to manually add type hints to third-party libraries that don't have them.
488+
489+
### Generating stub files
490+
491+
Mypy also ships with two tools for making it easier to create and maintain stubs: [Automatic stub generation (stubgen)](https://mypy.readthedocs.io/en/stable/stubgen.html#stubgen) and [Automatic stub testing (stubtest)](https://mypy.readthedocs.io/en/stable/stubtest.html#stubtest).
492+
493+
494+
```bash title="use stubgen to generate stub files for package my_pkg_dir"
495+
# default output dir is: out, use -o to change it
496+
stubgen my_pkg_dir -o stubs
497+
```
498+
499+
```bash title="use pyright to generate stub files for package my_pkg_dir"
500+
# default output dir is: typings
501+
pyright --createstub my_pkg_dir
502+
```
503+
504+
A common problem with stub files is that they tend to diverge from the actual implementation. Mypy includes the stubtest tool that can automatically check for discrepancies between the stubs and the implementation at runtime.
505+
506+
507+
481508
## Typing tools
482509

483510
### MyPy

0 commit comments

Comments
 (0)