# 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](https://peps.python.org/pep-0593/) により追加された。

- 型ヒントだけでは型と値の制約を1つの注釈に記述できない
  - pydanticでは制約を`Field(gt=0)`の形式でフィールドごとに記述する
  - FastAPIの従来の形式では制約をデフォルト値の位置に記述し、関数の直接の呼び出しでデフォルト値が`Query`のオブジェクトになる
- 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`として判定する。

```python
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`は説明用のクラスである。

```python
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](https://peps.python.org/pep-0593/#rationale) は、メタデータ`X`の解釈の手段がないツールに対し、`Annotated[T, X]`を`T`と同一に判定することを求めている。
型の注釈の判定を関数ごと無効にする`@no_type_check`と異なり、Annotatedでは`T`の型の判定と、ライブラリによる`X`の実行時の利用が両立する。
PEPの動機は型ヒント以外の用途の注釈（データベースの列との対応、他言語との橋渡しなど）と型ヒントの共存が困難だったことである。

```mermaid
flowchart LR
  A["Annotated[int, Field(gt=0)]"] --> T["型チェッカー"]
  A --> L["pydanticやFastAPI"]
  T --> TI["intとして型を判定<br/>Field(gt=0)は対象外"]
  L --> LI["Field(gt=0)を解釈<br/>実行時に値を検証"]
```

型チェッカーの判定の結果と、実行時の検証の結果は互いに独立である。

## get_type_hintsのinclude_extrasで実行時にメタデータを取得する

`typing.get_type_hints`はデフォルトではメタデータを除去し、[`include_extras=True`](https://docs.python.org/3/library/typing.html#typing.get_type_hints) の指定でAnnotatedのまま返す。

```python
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はエラーになる

[型の仕様](https://typing.python.org/en/latest/spec/qualifiers.html#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]`は、実行時と両方の型チェッカーでエラーになる。

```python
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](https://github.com/annotated-types/annotated-types) の`Gt(0)`を検証の制約として解釈する。
次の`Order`と`Stock`は説明用のモデルである。

```python
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](https://docs.pydantic.dev/latest/concepts/fields/#the-annotated-pattern) と呼んでいる。

## FastAPIではAnnotatedの形式でデフォルト値と制約を分離する

FastAPIの従来の形式では、クエリ引数の制約をデフォルト値の位置の`Query(...)`で記述した。
[FastAPI 0.95以降](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) のAnnotatedの形式では、制約を型の側に記述し、デフォルト値は`=`の右に記述する。
`Annotated[int, Query(default=1, ge=1)]`のように`Query`に`default`を指定すると、ルートの登録の時点で`AssertionError`になる。
次の図は2つの形式での制約とデフォルト値の記述の位置と、関数の直接の呼び出しの結果の対比である。

```mermaid
flowchart LR
  subgraph OLD["従来の形式"]
    O1["int = Query(default=1, ge=1)<br/>制約とデフォルト値を=の右に記述"] --> O2["直接の呼び出しで引数の値はQueryのオブジェクト"]
  end
  subgraph NEW["Annotatedの形式"]
    N1["Annotated[int, Query(ge=1)] = 1<br/>制約は型の側、デフォルト値は=の右"] --> N2["直接の呼び出しで引数の値は1"]
  end
```
次の`old_style`と`new_style`は、2つの形式の比較のための説明用の関数である。

```python
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の文書](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#advantages-of-annotated) もテストなどでの関数の直接の呼び出しをAnnotatedの利点としている。

### Dependsも型エイリアスにして複数のエンドポイントで共有する

次の`Session`と`get_session`は説明用のクラスと関数である。
依存性の注入の`Depends`もAnnotatedの型エイリアスにでき、複数のエンドポイントの引数に同一の依存を指定できる。

```python
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`](https://kdot.co.jp/kdotdev/python-newtype) である。

```python
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とは異なり、実行時のライブラリが値を検証する。
