# PythonのTypedDictのNotRequired・Optional・ReadOnlyの違い

## NotRequiredとOptionalの違いとは

Pythonの`TypedDict`の`NotRequired`はキーの省略の可否、`Optional`（`str | None`）は値が`None`であることの可否を指定し、2つは独立した指定である。
`ReadOnly`はキーへの代入・削除の可否を指定する。

- 省略できるキーの値の型を`str | None`にすると、キーのない辞書のリテラルは`Missing key`の型エラーになる
- `NotRequired`でキーの省略を指定すると、キーのない入力も型エラーにならない
  - `NotRequired[str]`のキーの値の`None`は型エラーである
  - 省略と`None`の両方を許可するキーは`NotRequired[str | None]`にする
- `ReadOnly`のキーへの代入・削除は型エラーになり、引数の型のキーを`ReadOnly`にした関数は、そのキーの値の型が部分型の`TypedDict`の値も引数にできる
- 3つの型修飾子は実行時には確認されず、必須のキーのない辞書や`ReadOnly`のキーへの代入も実行時は成功する
- `TypedDict`はデフォルトでは未定義のキーのある値も許容し、Python 3.15の`closed=True`で未定義のキーを禁止できる

## 前提となるTypedDictと型修飾子

### TypedDict

`TypedDict`とは、キーごとに値の型を指定した辞書の型である。
基本の使い方は [TypedDictの記事](https://kdot.co.jp/kdotdev/python-typed-dict) で説明した。

### 型修飾子

型修飾子（type qualifier）とは、値の型ではなくキーの性質を指定する`Required`・`NotRequired`・`ReadOnly`である。
`TypedDict`の定義のキーの型注釈だけに記述でき、`ReadOnly[NotRequired[int]]`のように2つ以上を同時に指定できる。
`Required`と`NotRequired`は [Python 3.11](https://peps.python.org/pep-0655/) 、`ReadOnly`は [Python 3.13](https://peps.python.org/pep-0705/) で`typing`に追加された。
それより前のバージョンでは、`typing_extensions`の`TypedDict`と型修飾子が必要である。

## 値のNoneとキーの省略は別の指定である

以降の例の診断はmypyとpyrightの標準の設定での出力で、Python 3.13以降（`closed`の例は3.15以降）を前提にする。

次の説明用の`User`は、`nickname`の値の型を`str | None`にしている。
`nickname`のない辞書は型エラーになり、値が`None`の辞書はエラーにならない。

```python
from typing import TypedDict


class User(TypedDict):
    name: str
    nickname: str | None


missing: User = {"name": "Ada"}
with_none: User = {"name": "Ada", "nickname": None}
# mypy
# error: Missing key "nickname" for TypedDict "User"  [typeddict-item]
# pyright
# error: Type "dict[str, str]" is not assignable to declared type "User"
#   "nickname" is required in "User" (reportAssignmentType)
```

`NotRequired[str]`にすると`nickname`は省略できるが、値の`None`は型エラーになる。

```python
from typing import NotRequired, TypedDict


class TextUser(TypedDict):
    nickname: NotRequired[str]


class NullableUser(TypedDict):
    nickname: NotRequired[str | None]


invalid: TextUser = {"nickname": None}
omitted: NullableUser = {}
nullable: NullableUser = {"nickname": None}
# mypy
# error: Incompatible types (expression has type "None", TypedDict item "nickname" has type "str")  [typeddict-item]
# pyright
# error: Type "dict[str, None]" is not assignable to declared type "TextUser"
#   "None" is not assignable to "str" (reportAssignmentType)
```

エラーになるのは`invalid`の行で、`NotRequired[str | None]`のキーは省略と`None`の両方を許可する。

[PEP 655](https://peps.python.org/pep-0655/#rationale) はTypeScriptの`year?: number`のような省略可能のキーの指定に`Optional`の語を採用しなかった。
理由は`Optional`が値の`None`の許可を意味する既存の語で、混同しやすいことである。
同じ理由で、PEP 655は`NotRequired[Optional[str]]`ではなく`NotRequired[str | None]`の記述を推奨している。

## NotRequiredのキーへのアクセス

`NotRequired`のキーの値は、`get`で取得するか、`in`でキーの存在を確認してから添字で取得する。

```python
from typing import NotRequired, TypedDict, reveal_type


class User(TypedDict):
    name: str
    nickname: NotRequired[str]


def show(user: User) -> None:
    reveal_type(user.get("nickname"))
    if "nickname" in user:
        reveal_type(user["nickname"])
    print(user["nickname"])
# mypy
# note: Revealed type is "str | None"
# note: Revealed type is "str"
# pyright
# information: Type of "user.get("nickname")" is "str | None"
# information: Type of "user["nickname"]" is "str"
# error: "nickname" is not a required key in "User", so access may result in runtime exception (reportTypedDictNotRequiredAccess)
```

`in`で確認せずに`user["nickname"]`を添字で参照すると、pyrightはエラーにし、mypyは標準の設定ではエラーにしない。
キーのない値の添字のアクセスは実行時に`KeyError`になる。
[型の仕様](https://typing.python.org/en/latest/spec/typeddict.html#supported-and-unsupported-operations) は確認の正確な規則を定めておらず、この差は仕様の違反ではない。

## total=FalseとRequired

`total=False`のクラスで宣言したキーは省略可能になり、必須のキーには`Required`を指定する。

```python
from typing import Required, TypedDict


class User(TypedDict, total=False):
    name: Required[str]
    nickname: str


missing: User = {"nickname": "a"}
valid: User = {"name": "Ada"}
# mypy
# error: Missing key "name" for TypedDict "User"  [typeddict-item]
# pyright
# error: Type "dict[str, str]" is not assignable to declared type "User"
#   "name" is required in "User" (reportAssignmentType)
```

[PEP 655](https://peps.python.org/pep-0655/#interaction-with-total-false) は`total=False`の定義を、そのクラスで宣言したキーに`NotRequired`を指定した定義と同等と定めている。
PEP 655は大半のキーが必須の定義には通常の定義と`NotRequired`、大半のキーが省略可能な定義には`total=False`と`Required`を推奨している。

## ReadOnlyで代入を禁止して値の型を共変にする

`ReadOnly`のキーへの代入は型エラーになり、通常のキーへの代入はエラーにならない。

```python
from typing import ReadOnly, TypedDict


class User(TypedDict):
    name: ReadOnly[str]
    nickname: str


def rename(user: User) -> None:
    user["name"] = "Grace"
    user["nickname"] = "g"
# mypy
# error: ReadOnly TypedDict key "name" TypedDict is mutated  [typeddict-readonly-mutated]
# pyright
# error: Could not assign item in TypedDict
#   "name" is a read-only key in "User" (reportTypedDictNotRequiredAccess)
```

[PEP 705の動機の節](https://peps.python.org/pep-0705/#pure-functions) は値の参照だけの関数の引数に、キーの型が少し異なる別の`TypedDict`の値を指定できないことを問題にしている。
次の例のキーの値の型が`int`の`A`の値は、キーの値の型が`int | str`の`B`の引数にできない。
通常のキーは値の型が部分型でも代入を許可せず、この関係を不変と呼ぶ。
`B`のキーを`ReadOnly[int | str]`にした`ReadonlyB`なら、`A`の値を引数にできる。

```python
from typing import ReadOnly, TypedDict


class A(TypedDict):
    x: int


class B(TypedDict):
    x: int | str


class ReadonlyB(TypedDict):
    x: ReadOnly[int | str]


def mutable(value: B) -> None: ...
def readonly(value: ReadonlyB) -> None: ...


value: A = {"x": 1}
mutable(value)
readonly(value)
# mypy
# error: Argument 1 to "mutable" has incompatible type "A"; expected "B"  [arg-type]
# pyright
# error: Argument of type "A" cannot be assigned to parameter "value" of type "B" in function "mutable"
#   "x" is an incompatible type
```

エラーになるのは`mutable(value)`の行である。
`B`を引数にする関数はキーに`str`の値を代入でき、`A`の値のキーの値が`str`になると`A`の型と矛盾する。
[PEP 705](https://peps.python.org/pep-0705/#type-consistency) は代入できないキーの値の型を`Sequence`と同様に共変と定めていて、その理由は`ReadOnly`のキーではこの矛盾が発生しないことである。

## 型修飾子は実行時に確認されない

`TypedDict`の型修飾子は実行時に辞書の内容を確認しない。
次の例では必須の`name`がない`missing = User()`と、`ReadOnly`のキーに代入する`user["name"] = "Grace"`が両方の型チェッカーでエラーになる。
どちらも実行は成功する。

```python
from typing import NotRequired, ReadOnly, TypedDict


class User(TypedDict):
    name: ReadOnly[str]
    nickname: NotRequired[str]


missing = User()
user: User = {"name": "Ada"}
user["name"] = "Grace"
print(missing, user)
print(sorted(User.__required_keys__), sorted(User.__readonly_keys__))
# 実行時の出力
# {} {'name': 'Grace'}
# ['name'] ['name']
```

`__required_keys__`・`__optional_keys__`・`__readonly_keys__`・`__mutable_keys__`のキーの集合は、実行時にも参照できる。
ただし辞書の内容は確認されないので、外部の入力は別に検証する。

## 未定義のキーとclosed

`TypedDict`はデフォルトでは未定義のキーのある値も許容する。
辞書のリテラルに未定義のキーを記述すると型エラーになるが、次の説明用の子クラス`ExtendedUser`の値を親の`User`の型の変数に代入すると、未定義のキーのある値が親の型の変数の値になる。

```python
from typing import TypedDict


class User(TypedDict):
    name: str


class ExtendedUser(User):
    role: str


extended: ExtendedUser = {"name": "Ada", "role": "admin"}
parent: User = extended
print(sorted(parent.keys()))
# 実行時の出力: ['name', 'role']
```

型チェッカーは`parent.keys()`の型を`dict_keys[str, object]`と判定する。
`name`以外のキーの存在が前提である。
[PEP 728の動機の節](https://peps.python.org/pep-0728/#motivation) はこの性質の問題を2つ指摘している。
`.items()`や`.values()`の型を正確に推論できないことと、`in`による型の絞り込みが安全でないことである。
Python 3.15で追加された [PEP 728](https://peps.python.org/pep-0728/) の`closed=True`を指定すると、`TypedDict`の未定義のキーを禁止できる。
次の説明用の`ClosedUser`への、未定義のキーのある別の`TypedDict`の値の代入は、両方の型チェッカーでエラーになる。

```python
from typing import TypedDict


class ClosedUser(TypedDict, closed=True):
    name: str


class ExtendedUser(TypedDict):
    name: str
    role: str


extended: ExtendedUser = {"name": "Ada", "role": "admin"}
closed: ClosedUser = extended
# mypy
# error: Incompatible types in assignment (expression has type "ExtendedUser", variable has type "ClosedUser")  [assignment]
# pyright
# error: Type "ExtendedUser" is not assignable to declared type "ClosedUser"
```

同じPEPの`extra_items=int`は、未定義のキーの値の型を指定する。
mypy 2.4ではクラスの引数そのものが`Unexpected keyword argument "extra_items"`のエラーになり、pyrightだけが値の型を確認する。

## キーの性質ごとの記述

| キーの性質 | 記述 |
|---|---|
| 必須で、値は`None`の場合がある | `nickname: str \| None` |
| 省略可能で、値は`None`にならない | `nickname: NotRequired[str]` |
| 省略可能で、値は`None`の場合がある | `nickname: NotRequired[str \| None]` |
| 大半のキーが省略可能 | `total=False`と、必須のキーの`Required` |
| 関数が変更しないキー | `ReadOnly[...]` |
| 未定義のキーを禁止する | Python 3.15の`closed=True` |

TypeScriptでは省略可能のキーを`nickname?: string`、値の`null`を`nickname: string | null`、代入の禁止を`readonly`で記述する。
