CLOVER🍀

That was when it all began.

Mypyとスタブファイルとtypeshedと

これは、なにをしたくて書いたもの?

前に、Pythonでの型ヒントとMypyを扱ってみました。

Pythonで型ヒント(Type Hints)を試してみる(+Mypy) - CLOVER🍀

またPyMySQLを扱った時に、型情報としてtypes-PyMySQLをインストールしています。

PyMySQLを使って、PythonからMySQLに接続してみる - CLOVER🍀

この時は軽く流していたのですが、この型情報について見ていきたいと思います。今回は調べた記録を残すくらいにしておきますが。

Mypyとスタブファイルとtypeshedと

Mypyはtypeshedリポジトリーにあるスタブファイルを使って、標準ライブラリーやサードパーティーのライブラリーの関数、クラスなどの
型定義を決めるようです。

Mypy uses stub files stored in the typeshed repository to determine the types of standard library and third-party library functions, classes, and other definitions.

Stub files - mypy 1.13.0 documentation

typeshedのGitHubリポジトリーはこちらですね。

GitHub - python/typeshed: Collection of library stubs for Python, with static types

typeshedはPythonの標準ライブラリーやビルトイン、サードパーティーのライブラリーの型アノテーションが含まれるリポジトリーです。

Typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as contributed by people external to those projects.

typeshedに含まれるデータを使うことで、静的解析や型チェックなどに利用できるということですね。

This data can e.g. be used for static analysis, type checking, type inference, and autocompletion.

リリースは自動的に行われるようです。

These PyPI packages follow PEP 561 and are automatically released (up to once a day) by typeshed internal machinery.

話をスタブファイルに戻します。

スタブファイルの書き方はこんな感じのようです。スタブファイルの拡張子は.pyiです。

# Variables with annotations do not need to be assigned a value.
# So by convention, we omit them in the stub file.
x: int

# Function bodies cannot be completely removed. By convention,
# we replace them with `...` instead of the `pass` statement.
def func_1(code: str) -> int: ...

# We can do the same with default arguments.
def func_2(a: int, b: int = ...) -> int: ...

Stub files / Stub file syntax

スタブファイルは通常のPythonの構文で書くことができ、初期化子や関数本体、デフォルト引数のような実行時の処理は省略されるようです。

Stub files are written in normal Python syntax, but generally leaving out runtime logic like variable initializers, function bodies, and default arguments.

ランタイムのロジックの一部を完全に省略できない場合は、...を使用して置き換えることができるようです。

If it is not possible to completely leave out some piece of runtime logic, the recommended convention is to replace or elide them with ellipsis expressions (...).

typeshedにあるスタブファイルの記述例を見てみましょう。

requests。

https://github.com/python/typeshed/blob/main/stubs/requests/requests/api.pyi

PyMySQL。

https://github.com/python/typeshed/blob/main/stubs/PyMySQL/pymysql/connections.pyi

typeshedにある型定義のパッケージ名は、types-が先頭に付与されたものになります。

types-requeststypes-PyMySQLですね。

最後はMypyのドキュメントで気にしておいた方がよさそうなものを並べておきます。

スタブファイルの自動生成。

Automatic stub generation (stubgen) - mypy 1.13.0 documentation

スタブファイルのテスト。これはスタブファイルが実際の実装から逸脱する傾向があるため、チェックが必要いうことのようです。

Automatic stub testing (stubtest) - mypy 1.13.0 documentation

インストールしたパッケージについて。

Using installed packages - mypy 1.13.0 documentation

簡単でしたが、今回はこんなところでしょうか。