Skip to content

Commit 1e6a03d

Browse files
committed
python typing / add cheat sheet
1 parent 95f6dac commit 1e6a03d

File tree

1 file changed

+34
-30
lines changed

1 file changed

+34
-30
lines changed

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

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Python is a dynamically typed language, meaning variable types don't require exp
1616

1717
Type hints ([PEP 484](https://peps.python.org/pep-0484/)) have been a major focus of recent Python releases, and I was particularly intrigued when I heard about [Guido van Rossum's work on MyPy at Dropbox](https://blog.dropbox.com/topics/company/thank-you--guido), where the team needed robust tooling to migrate their codebase from Python 2 to Python 3.
1818

19-
Today, type hints are essential for modern Python development. They significantly enhance IDE capabilities and AI-powered development tools by providing better code completion, static analysis, and error detection. This mirrors the evolution we've seen with TypeScript's adoption over traditional JavaScript—explicit typing leads to more reliable and maintainable code.
19+
Today, type hints are [essential for modern Python development](https://mypy.readthedocs.io/en/stable/faq.html#would-my-project-benefit-from-static-typing). They significantly enhance IDE capabilities and AI-powered development tools by providing better code completion, static analysis, and error detection. This mirrors the evolution we've seen with TypeScript's adoption over traditional JavaScript—explicit typing leads to more reliable and maintainable code.
2020

2121
The majority of this post is based on [MyPy documentation](https://mypy.readthedocs.io/).
2222

@@ -25,6 +25,10 @@ The majority of this post is based on [MyPy documentation](https://mypy.readthed
2525

2626
<!-- more -->
2727

28+
## Type hints cheat sheet
29+
30+
Ref: https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
31+
2832
## typing module vs collections module
2933

3034
Since Python 3.9, most of types in `typing` module i [deprecated](https://docs.python.org/3/library/typing.html#deprecated-aliases), and `collections` module is recommended.
@@ -509,34 +513,6 @@ def maybe_direction(x: str) -> None:
509513
print(f"{x} is not a cardinal direction")
510514
```
511515

512-
## Stub files
513-
514-
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.
515-
516-
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`.
517-
518-
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.
519-
520-
### Generating stub files
521-
522-
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).
523-
524-
```bash title="use stubgen to generate stub files for package my_pkg_dir"
525-
# default output dir is: out, use -o to change it
526-
stubgen my_pkg_dir -o stubs
527-
```
528-
529-
```bash title="use pyright to generate stub files for package my_pkg_dir"
530-
# default output dir is: typings
531-
pyright --createstub my_pkg_dir
532-
```
533-
534-
A common problem with stub files is that they tend to diverge from the actual implementation. Mypy includes the [stubtest](https://mypy.readthedocs.io/en/stable/stubtest.html#stubtest) tool that can automatically check for discrepancies between the stubs and the implementation at runtime.
535-
536-
```bash
537-
MYPYPATH=stubs stubtest my_pkg_dir --concise
538-
```
539-
540516
## Generics
541517

542518
`list`, `set`, `dict`, etc, all the built-in collection classes are all Generics type, as they accept one or more type arguments within [...], which can be arbitrary types.
@@ -707,7 +683,35 @@ def process(w: Wrapper[int] | Wrapper[str]) -> None:
707683
reveal_type(w) # Revealed type is "Wrapper[str]"
708684
```
709685

710-
And check [this Pydantic doc](https://docs.pydantic.dev/latest/concepts/unions/#discriminated-unions-with-str-discriminators) to see how Pydantic use `Field(discriminator='...')` to handle discriminators.
686+
And check [this Pydantic documentation](https://docs.pydantic.dev/latest/concepts/unions/#discriminated-unions-with-str-discriminators) to see how Pydantic uses `Field(discriminator='...')` to handle discriminated unions.
687+
688+
## Stub files
689+
690+
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.
691+
692+
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`.
693+
694+
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.
695+
696+
### Generating stub files
697+
698+
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).
699+
700+
```bash title="use stubgen to generate stub files for package my_pkg_dir"
701+
# default output dir is: out, use -o to change it
702+
stubgen my_pkg_dir -o stubs
703+
```
704+
705+
```bash title="use pyright to generate stub files for package my_pkg_dir"
706+
# default output dir is: typings
707+
pyright --createstub my_pkg_dir
708+
```
709+
710+
A common problem with stub files is that they tend to diverge from the actual implementation. Mypy includes the [stubtest](https://mypy.readthedocs.io/en/stable/stubtest.html#stubtest) tool that can automatically check for discrepancies between the stubs and the implementation at runtime.
711+
712+
```bash
713+
MYPYPATH=stubs stubtest my_pkg_dir --concise
714+
```
711715

712716
## Typing tools
713717

0 commit comments

Comments
 (0)