型ヒント(PEP 484 以降)を使うと、変数、関数の引数、戻り値の期待される型を注釈できます。これらは任意であり、実行時には強制されません(Python は実行時に無視します)が、静的解析、より良いツール連携、より明確なコードを可能にします。
基本構文
() -> :
name * times
age: =
names: [] = [, ]
scores: [, ] = {: }
: type は引数/変数を注釈し、-> type は戻り値を注釈します。これらは意図を文書化し、ツールによってチェックされますが、Python は実行時に強制しません(間違った型を渡してもそれ自体ではエラーになりません)。
from typing import Optional, Union, Callable, Any
def find(id: int) -> Optional[str]: # str OR None (= str | None in 3.10+)
...
x: int | str # Union (3.10+ syntax)
handler: Callable[[int], bool] # a function taking int, returning bool
items: list[dict[str, int]] # nested generics
def add(a: int, b: int) -> int:
return a + b
add("hello", 3) # ✅ Python runs it (and crashes); ❌ mypy/pyright flags it BEFORE running
mypy や pyright のような型チェッカーは、ヒントを解析してコードを実行する前に型エラーを報告します。これにより、コンパイラのように、あるクラスのバグ(誤った引数の型、None の誤用)を早期に捕捉できます。
✓ Catch type bugs early via static checkers (mypy, pyright) — before runtime
✓ IDE support — better autocomplete, refactoring, inline error detection
✓ Self-documenting code — signatures show exactly what's expected/returned
✓ Powers frameworks — FastAPI/Pydantic USE hints for validation & docs
✓ Easier maintenance of large codebases (catch breaking changes)
You can add hints incrementally — a few functions, or strictly everywhere.
Unannotated code still works. "Gradual typing" suits adopting them over time.
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int # Pydantic USES the hint to VALIDATE data at runtime
User(name="Ann", age="x") # raises a validation error
一部のライブラリ(Pydantic、FastAPI)は型ヒントを読み取ってデータを検証し、ドキュメントを生成します。これにより型ヒントが実行時に機能的な意味を持つようになります。
型ヒントは、Python の動的な柔軟性を犠牲にすることなく、静的型付けの多くの利点をもたらします。型に関連するバグを早期に捕捉し(mypy/pyright 経由)、IDE のツール連携とリファクタリングを大幅に改善し、生きたドキュメントとして機能し、検証と自動生成ドキュメントにそれらを使う現代的なフレームワーク(FastAPI、Pydantic)を支えます。
任意であり Python 自体によって実行時に強制されないものの、型ヒントはコードをより信頼でき、保守しやすく、自己文書化されたものにするため、プロフェッショナルで大規模な Python コードベースで標準的になっています。プロジェクトが成長するにつれて、ますます期待される慣行となっています。