PythonのAnnotatedで型にメタデータを付加する

Annotatedとは
PythonのAnnotatedとは、型に任意の値(メタデータ)を付加する仕組みである。
メタデータには文字列、自作のクラスのインスタンス、pydanticのField(gt=0)のようなライブラリのオブジェクトを指定できる。
Annotated[int, Field(gt=0)]の型は型チェッカーにとってintで、付加したField(gt=0)は実行時にpydanticなどのライブラリが解釈する。
typing.AnnotatedはPython 3.9で PEP 593 により追加された。
- 型ヒントだけでは型と値の制約を1つの注釈に記述できない
- pydanticでは制約を
Field(gt=0)の形式でフィールドごとに記述する - FastAPIの従来の形式では制約をデフォルト値の位置に記述し、関数の直接の呼び出しでデフォルト値が
Queryのオブジェクトになる
- pydanticでは制約を
- Annotatedで型と制約を1つの式に記述すると、制約付きの型を型エイリアスにして複数のモデルや関数で再利用できる
- mypyとpyrightはメタデータを無視し、
Annotated[T, X]の型をTと判定する- pydanticやFastAPIは、実行時にメタデータを取得して検証の規則にする
- メタデータは1個以上が必須で、ネストした
Annotatedは1つに平坦化される
Annotated[int, Field(gt=0)]の引数に-1を指定しても型エラーにならない- 値を検証するのは、pydanticやFastAPIのようなメタデータを解釈するライブラリだけである
- 同じ
intの値の混同を型エラーにする手段の1つがNewTypeである
型チェッカーはメタデータを無視する
以降の例の診断はmypyの--strictとpyrightの標準の設定での出力である。
例のコードはPython 3.11以降を前提にする(reveal_typeは3.11でtypingに追加された)。
次のMetaは説明用の型エイリアスで、型チェッカーはintとして判定する。
from typing import Annotated, reveal_type
Meta = Annotated[int, "meta"]
x: Meta = 3
y = x * 2 + 1
reveal_type(x)
bad: Meta = "3"
# mypy
# note: Revealed type is "builtins.int"
# error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
# pyright
# information: Type of "x" is "Literal[3]"
# error: Type "Literal['3']" is not assignable to declared type "Meta" (reportAssignmentType)
intの演算はエラーにならず、strの代入は両方の型チェッカーがエラーにする。
pyrightのLiteral[3]は代入の値による型の限定の結果で、Annotatedの解釈の違いではない。
自作のメタデータの制約も型チェッカーの判定の対象外である。
次のValueRangeは説明用のクラスである。
from dataclasses import dataclass
from typing import Annotated
@dataclass(frozen=True)
class ValueRange:
lo: int
hi: int
Score = Annotated[int, ValueRange(0, 10)]
def set_score(s: Score) -> int:
return s
print(set_score(-1))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# -1
PEP 593のRationale は、メタデータXの解釈の手段がないツールに対し、Annotated[T, X]をTと同一に判定することを求めている。
型の注釈の判定を関数ごと無効にする@no_type_checkと異なり、AnnotatedではTの型の判定と、ライブラリによるXの実行時の利用が両立する。
PEPの動機は型ヒント以外の用途の注釈(データベースの列との対応、他言語との橋渡しなど)と型ヒントの共存が困難だったことである。
Field(gt=0)は対象外"] L --> LI["Field(gt=0)を解釈
実行時に値を検証"]
型チェッカーの判定の結果と、実行時の検証の結果は互いに独立である。
get_type_hintsのinclude_extrasで実行時にメタデータを取得する
typing.get_type_hintsはデフォルトではメタデータを除去し、include_extras=True の指定でAnnotatedのまま返す。
from typing import Annotated, get_args, get_origin, get_type_hints
def f(x: Annotated[int, "unit:cm"], y: str) -> float:
return x / 1
print(get_type_hints(f))
hints = get_type_hints(f, include_extras=True)
print(hints["x"])
print(hints["x"].__metadata__)
print(get_args(hints["x"]), get_origin(hints["x"]) is Annotated)
# 実行時
# {'x': <class 'int'>, 'y': <class 'str'>, 'return': <class 'float'>}
# typing.Annotated[int, 'unit:cm']
# ('unit:cm',)
# (<class 'int'>, 'unit:cm') True
メタデータのないAnnotatedはエラーになる
型の仕様 の規則は次のとおりである。
| 規則 | 例 | 結果 |
|---|---|---|
| メタデータは1個以上 | Annotated[int] |
実行時にTypeError、型チェッカーもエラー |
| ネストは平坦化される | Annotated[Annotated[int, A], B] |
Annotated[int, A, B]と同一 |
| メタデータの順序は保持される | Annotated[int, A, B]とAnnotated[int, B, A] |
実行時の==で等しくない |
平坦化により、型エイリアスにメタデータを追加したAnnotated[PositiveInt, X]も1段のAnnotatedになる。
メタデータのないAnnotated[int]は、実行時と両方の型チェッカーでエラーになる。
from typing import Annotated
x: Annotated[int] = 1
# 実行時
# TypeError: Annotated[...] should be used with at least two arguments (a type and an annotation).
# mypy
# error: Annotated[...] must have exactly one type argument and at least one annotation [valid-type]
# pyright
# error: Expected one type argument and one or more annotations for "Annotated" (reportInvalidTypeForm)
Bad = Annotated[int]のように型エイリアスとして定義した場合、pyrightは定義の行をエラーにし、mypyの--strictはエラーにしない。
pydanticでは制約付きの型を型エイリアスにして再利用する
pydantic v2はAnnotatedのメタデータのField(gt=0)や annotated-types のGt(0)を検証の制約として解釈する。
次のOrderとStockは説明用のモデルである。
from typing import Annotated
import annotated_types
from pydantic import BaseModel, Field, ValidationError
PositiveInt = Annotated[int, Field(gt=0)]
PositiveIntAT = Annotated[int, annotated_types.Gt(0)]
class Order(BaseModel):
qty: PositiveInt
qty2: PositiveIntAT
class Stock(BaseModel):
count: PositiveInt
cases: list[tuple[type[BaseModel], dict[str, int]]] = [
(Order, {"qty": 0, "qty2": 0}),
(Stock, {"count": 0}),
]
for model, data in cases:
try:
model.model_validate(data)
except ValidationError as error:
for e in error.errors():
print(model.__name__, e["loc"], e["type"])
# 実行時
# Order ('qty',) greater_than
# Order ('qty2',) greater_than
# Stock ('count',) greater_than
qty: int = Field(gt=0)の形式では、制約をフィールドごとに記述する。
Annotatedの型エイリアスPositiveIntは、OrderとStockの両方のフィールドに同一の制約を適用する。
型チェッカーはPositiveIntをintと判定する。
pydanticは解釈の手段のないメタデータを無視する(自作のValueRangeの制約は検証の対象外で、-1も検証のエラーにならない)。
pydanticの文書はこの記述を annotated pattern と呼んでいる。
FastAPIではAnnotatedの形式でデフォルト値と制約を分離する
FastAPIの従来の形式では、クエリ引数の制約をデフォルト値の位置のQuery(...)で記述した。
FastAPI 0.95以降 のAnnotatedの形式では、制約を型の側に記述し、デフォルト値は=の右に記述する。
Annotated[int, Query(default=1, ge=1)]のようにQueryにdefaultを指定すると、ルートの登録の時点でAssertionErrorになる。
次の図は2つの形式での制約とデフォルト値の記述の位置と、関数の直接の呼び出しの結果の対比である。
制約とデフォルト値を=の右に記述"] --> O2["直接の呼び出しで引数の値はQueryのオブジェクト"] end subgraph NEW["Annotatedの形式"] N1["Annotated[int, Query(ge=1)] = 1
制約は型の側、デフォルト値は=の右"] --> N2["直接の呼び出しで引数の値は1"] end
次のold_styleとnew_styleは、2つの形式の比較のための説明用の関数である。
from typing import Annotated
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/old")
def old_style(q: int = Query(default=1, ge=1)) -> int:
return q
@app.get("/new")
def new_style(q: Annotated[int, Query(ge=1)] = 1) -> int:
return q
print(repr(old_style()), repr(new_style()))
# 実行時
# Query(1) 1
HTTPのリクエストではどちらもq=0で422、qの省略で200になる。
FastAPIの外から関数を直接呼び出すと、従来の形式ではデフォルト値がQueryのオブジェクトになり、old_style() + 1はTypeErrorになる。
従来の形式のデフォルト値のQuery(...)は両方の型チェッカーでエラーにならないので、old_style() + 1のTypeErrorは実行時まで発見できない。
FastAPIの文書 もテストなどでの関数の直接の呼び出しをAnnotatedの利点としている。
Dependsも型エイリアスにして複数のエンドポイントで共有する
次のSessionとget_sessionは説明用のクラスと関数である。
依存性の注入のDependsもAnnotatedの型エイリアスにでき、複数のエンドポイントの引数に同一の依存を指定できる。
from typing import Annotated
from fastapi import Depends, FastAPI, Query
class Session:
def __init__(self, name: str) -> None:
self.name = name
def get_session() -> Session:
return Session("db")
SessionDep = Annotated[Session, Depends(get_session)]
PageNo = Annotated[int, Query(ge=1)]
app = FastAPI()
@app.get("/items")
def list_items(session: SessionDep, q: PageNo = 1) -> dict[str, str | int]:
return {"session": session.name, "q": q}
@app.get("/users")
def list_users(session: SessionDep, q: PageNo) -> dict[str, str | int]:
return {"session": session.name, "q": q}
# /items?q=0 → 422(greater_than_equal)
# /users → 422(missing、デフォルト値のない必須の引数)
Annotatedの型エイリアスはintと区別されない
型チェッカーはAnnotatedの型エイリアスをTと同一の型と判定するので、list[int]の値をlist[PositiveInt]の引数に指定してもエラーにならない。
intと区別する手段の1つが NewType である。
from typing import Annotated, NewType
from annotated_types import Gt
PositiveInt = Annotated[int, Gt(0)]
UserId = NewType("UserId", int)
def total(values: list[PositiveInt]) -> int:
return sum(values)
def find_user(user_id: UserId) -> str:
return f"user {user_id}"
raw: list[int] = [-1, 2]
print(total(raw))
n: int = 42
print(find_user(n))
# mypy
# error: Argument 1 to "find_user" has incompatible type "int"; expected "UserId" [arg-type]
# pyright
# error: Argument of type "Literal[42]" cannot be assigned to parameter "user_id" of type "UserId" in function "find_user" (reportArgumentType)
total(raw)は両方の型チェッカーでエラーにならず、実行時の結果は1である。
NewTypeの型は型チェッカーが別の型と判定するが、値の制約は判定の対象外である。
通常の関数の引数はpydanticのvalidate_callかTypeAdapterで検証できる。
| 目的 | 指定 |
|---|---|
| 実行時の検証やAPIの定義で制約を利用する | Annotated[int, Gt(0)] |
同じintの値で用途の異なる値の混同を型エラーにする |
NewType("UserId", int) |
| 両方が必要 | Annotated[UserId, Gt(0)](TypeAdapterで0を拒否する) |
型理論のrefinement type(値の範囲付きの型)との違い
値の範囲を型の一部にする仕組みは、型理論ではrefinement typeと呼ばれる。
Annotatedの制約は型の判定の対象外で、refinement typeとは異なり、実行時のライブラリが値を検証する。


