TypedDict, Required, NotRequired and ReadOnly

suggest change

A lot of Python data is a plain dict with a fixed set of string keys: parsed JSON, API responses, config files, rows from a database driver, **kwargs. Hinting those as dict[str, Any] tells the type checker nothing. A TypedDict describes the keys and the type of each value, so the checker can catch typos in key names, missing keys and wrong value types, while at runtime the value stays an ordinary dict.

The feature has grown over several releases:

All of these are also available on older Pythons from the typing_extensions package.

Examples were run with Python 3.13. Type checker output is from mypy 2.4 and pyright 1.1.414.

Defining a TypedDict

Subclass TypedDict and list the keys as annotated class attributes:

import json
from typing import TypedDict

class Movie(TypedDict):
    title: str
    year: int
    rating: float

def describe(movie: Movie) -> str:
    return f"{movie['title']} ({movie['year']}): {movie['rating']:.1f}"

m: Movie = {"title": "Alien", "year": 1979, "rating": 8.5}
print(describe(m))
print(type(m), m)

data: Movie = json.loads('{"title": "Heat", "year": 1995, "rating": 8.3}')
print(describe(data))
print(sorted(Movie.__required_keys__))
print(Movie.__annotations__)
Alien (1979): 8.5
<class 'dict'> {'title': 'Alien', 'year': 1979, 'rating': 8.5}
Heat (1995): 8.3
['rating', 'title', 'year']
{'title': <class 'str'>, 'year': <class 'int'>, 'rating': <class 'float'>}

Note what is not happening: Movie is not a class you instantiate with attributes. m is created with a dict literal, its type is dict, and you read values with movie["title"], not movie.title. All the benefit comes from the type checker. You can also call Movie(title="Alien", year=1979, rating=8.5), which just returns a dict.

Here is what a type checker reports when the data doesn't match:

from typing import TypedDict

class Movie(TypedDict):
    title: str
    year: int
    rating: float

a: Movie = {"title": "Alien", "year": "1979", "rating": 8.5}
b: Movie = {"title": "Alien", "rating": 8.5}
c: Movie = {"title": "Alien", "year": 1979, "rating": 8.5, "director": "Scott"}

def show(movie: Movie) -> None:
    print(movie["titel"])
    movie["year"] = "next year"
    del movie["title"]
    reveal_type(movie["rating"])
$ mypy app.py
app.py:8: error: Incompatible types (expression has type "str", TypedDict item "year" has type "int")  [typeddict-item]
app.py:9: error: Missing key "year" for TypedDict "Movie"  [typeddict-item]
app.py:10: error: Extra key "director" for TypedDict "Movie"  [typeddict-unknown-key]
app.py:13: error: TypedDict "Movie" has no key "titel"  [typeddict-item]
app.py:13: note: Did you mean "title"?
app.py:14: error: Value of "year" has incompatible type "str"; expected "int"  [typeddict-item]
app.py:15: error: Key "title" of TypedDict "Movie" cannot be deleted  [misc]
app.py:16: note: Revealed type is "float"
Found 6 errors in 1 file (checked 1 source file)

Every key access is checked, and movie["rating"] has the type float, not Any. With dict[str, Any] none of these mistakes would be reported.

The functional syntax

Keys that aren't valid Python identifiers ("content-type", "class", "from") can't be written as class attributes. Use the functional form, which takes a dict of key names to types:

from typing import TypedDict

Headers = TypedDict("Headers", {"content-type": str, "content-length": int})
Attrs = TypedDict("Attrs", {"class": str, "id": str}, total=False)

h: Headers = {"content-type": "text/html", "content-length": 512}
a: Attrs = {"class": "btn"}
print(h["content-type"], a)
print(Headers.__name__, sorted(Headers.__required_keys__))
print(sorted(Attrs.__optional_keys__))
text/html {'class': 'btn'}
Headers ['content-length', 'content-type']
['class', 'id']

The first argument must match the variable name. The old keyword form, TypedDict("Point", x=int, y=int), was removed in Python 3.13.

Optional keys: total=False, Required and NotRequired

By default every key is required. There are two ways to mark keys that may be absent:

from typing import NotRequired, Required, TypedDict

class User(TypedDict):
    id: int
    name: str
    email: NotRequired[str]
    nickname: NotRequired[str | None]

class UserPatch(TypedDict, total=False):
    id: Required[int]
    name: str
    email: str

u1: User = {"id": 1, "name": "Ann"}
u2: User = {"id": 2, "name": "Bob", "email": "bob@example.com", "nickname": None}
p: UserPatch = {"id": 1, "email": "ann@example.org"}

for cls in (User, UserPatch):
    print(cls.__name__, "required:", sorted(cls.__required_keys__),
          "optional:", sorted(cls.__optional_keys__))
print(u1, u2, p)
User required: ['id', 'name'] optional: ['email', 'nickname']
UserPatch required: ['id'] optional: ['email', 'name']
{'id': 1, 'name': 'Ann'} {'id': 2, 'name': 'Bob', 'email': 'bob@example.com', 'nickname': None} {'id': 1, 'email': 'ann@example.org'}

Pick whichever needs fewer annotations: NotRequired when most keys are required, total=False plus Required when most are optional (like a PATCH request body).

"Optional key" and "optional value" are different things:

Before Python 3.11, total=False was the only way to get optional keys, so you had to split a TypedDict into a total base class and a non-total subclass. Required/NotRequired make that unnecessary.

Reading optional keys safely

A type checker should stop you from reading an optional key with d[key], because that raises KeyError when the key is missing. Check with in first, or use .get():

from typing import NotRequired, TypedDict

class User(TypedDict):
    id: int
    name: str
    email: NotRequired[str]

def contact(user: User) -> str:
    return user["email"]

def contact_safe(user: User) -> str:
    if "email" in user:
        return user["email"]
    return user.get("email", "no email")

def maybe_email(user: User) -> None:
    reveal_type(user.get("email"))
    reveal_type(user.get("name"))
    del user["email"]
    del user["name"]

missing: User = {"id": 1}
$ pyright app.py
  app.py:9:12 - error: Could not access item in TypedDict
    "email" is not a required key in "User", so access may result in runtime exception (reportTypedDictNotRequiredAccess)
  app.py:17:17 - information: Type of "user.get("email")" is "str | None"
  app.py:18:17 - information: Type of "user.get("name")" is "str"
  app.py:20:9 - error: Could not delete item in TypedDict
    "name" is a required key and cannot be deleted (reportGeneralTypeIssues)
  app.py:22:17 - error: Type "dict[str, int]" is not assignable to declared type "User"
    "name" is required in "User" (reportAssignmentType)
3 errors, 0 warnings, 2 informations
$ mypy app.py
app.py:17: note: Revealed type is "str | None"
app.py:18: note: Revealed type is "str"
app.py:20: error: Key "name" of TypedDict "User" cannot be deleted  [misc]
app.py:22: error: Missing key "name" for TypedDict "User"  [typeddict-item]
Found 2 errors in 1 file (checked 1 source file)

Both checkers understand that "email" in user narrows the type so that user["email"] is safe, that .get() of an optional key may return None, and that only optional keys can be deleted. But note the difference on line 9: pyright reports user["email"] on an unchecked optional key, mypy does not. If you use mypy, prefer .get() for optional keys out of habit.

Inheritance and generic TypedDicts

A TypedDict can extend one or more other TypedDicts. The child gets all the parent keys, and each key keeps the totality of the class it was declared in:

from typing import NotRequired, TypedDict

class Point2D(TypedDict):
    x: float
    y: float

class Point3D(Point2D):
    z: float

class Labeled(TypedDict, total=False):
    label: str
    color: str

class Marker(Point2D, Labeled):
    size: NotRequired[int]

class Page[T](TypedDict):
    items: list[T]
    total: int
    next: str | None

p: Point3D = {"x": 1.0, "y": 2.0, "z": 3.0}
m: Marker = {"x": 0, "y": 0, "label": "origin"}
page: Page[Point2D] = {"items": [{"x": 1, "y": 2}], "total": 1, "next": None}

print(p, m, page, sep="\n")
print(sorted(Marker.__required_keys__), sorted(Marker.__optional_keys__))
print(Point3D.__mro__)
print(Page[int])

def norm(pt: Point2D) -> float:
    return (pt["x"] ** 2 + pt["y"] ** 2) ** 0.5

print(norm(p))
{'x': 1.0, 'y': 2.0, 'z': 3.0}
{'x': 0, 'y': 0, 'label': 'origin'}
{'items': [{'x': 1, 'y': 2}], 'total': 1, 'next': None}
['x', 'y'] ['color', 'label', 'size']
(<class '__main__.Point3D'>, <class 'dict'>, <class 'object'>)
__main__.Page[int]
2.23606797749979

A few things to note:

Compatibility rules

Structural typing has two rules that surprise people. A mutable key must have exactly the same type in both TypedDicts, and a TypedDict is not a dict[str, Any]:

from collections.abc import Mapping
from typing import Any, TypedDict

class Point2D(TypedDict):
    x: float
    y: float

class IntPoint(TypedDict):
    x: int
    y: int

def norm(pt: Point2D) -> float:
    return (pt["x"] ** 2 + pt["y"] ** 2) ** 0.5

def dump(d: dict[str, Any]) -> None: ...
def dump_ro(d: Mapping[str, object]) -> None: ...

ip: IntPoint = {"x": 3, "y": 4}
norm(ip)
pt: Point2D = {"x": 1.5, "y": 2.0}
dump(pt)
dump_ro(pt)
$ mypy app.py
app.py:19: error: Argument 1 to "norm" has incompatible type "IntPoint"; expected "Point2D"  [arg-type]
app.py:21: error: Argument 1 to "dump" has incompatible type "Point2D"; expected "dict[str, Any]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Both errors protect you from real bugs. norm() could execute pt["x"] = 0.5, which would put a float into an IntPoint. dump() could do d["x"] = "oops" or d.clear(). Accepting a read-only Mapping[str, object] works, because it promises not to modify anything. The next section shows how to make the first case work too.

ReadOnly keys

ReadOnly[T] (Python 3.13) marks a key that must not be assigned or deleted through this type:

from typing import NotRequired, ReadOnly, TypedDict

class Config(TypedDict):
    name: ReadOnly[str]
    port: int
    debug: ReadOnly[NotRequired[bool]]

def bump(cfg: Config) -> None:
    cfg["port"] += 1
    cfg["name"] = "other"
    del cfg["debug"]

cfg: Config = {"name": "api", "port": 8000, "debug": True}
bump(cfg)
print(cfg)
print(sorted(Config.__readonly_keys__), sorted(Config.__mutable_keys__))
print(sorted(Config.__required_keys__), sorted(Config.__optional_keys__))
$ mypy app.py
app.py:10: error: ReadOnly TypedDict key "name" TypedDict is mutated  [typeddict-readonly-mutated]
app.py:11: error: Key "debug" of TypedDict "Config" cannot be deleted  [misc]
Found 2 errors in 1 file (checked 1 source file)

ReadOnly combines with Required/NotRequired in either order. Like everything else here, it is not enforced at runtime. Running the program anyway modifies the dict:

{'name': 'other', 'port': 8001}
['debug', 'name'] ['port']
['name', 'port'] ['debug']

ReadOnly is not like a frozen dataclass. It means "code that sees the dict through this type won't change this key", which is exactly what a function that only reads its argument promises. Because nothing writes through a read-only key, its type can be covariant: a TypedDict with x: int is accepted where x: ReadOnly[float] is expected. That fixes the IntPoint error from the previous section:

from typing import ReadOnly, TypedDict

class Point2D(TypedDict):
    x: ReadOnly[float]
    y: ReadOnly[float]

class IntPoint(TypedDict):
    x: int
    y: int

class Labeled(TypedDict):
    x: int
    y: int
    label: str

def norm(pt: Point2D) -> float:
    return (pt["x"] ** 2 + pt["y"] ** 2) ** 0.5

ip: IntPoint = {"x": 3, "y": 4}
lp: Labeled = {"x": 6, "y": 8, "label": "p"}
print(norm(ip), norm(lp))
5.0 10.0

mypy reports no errors. A good rule: when a function only reads a TypedDict, declare the parameter type with ReadOnly keys so it accepts as many callers as possible.

The same covariance applies to inheritance. A subclass may narrow the type of a read-only key, for example to a Literal tag, but not the type of a mutable one:

from typing import Literal, ReadOnly, TypedDict

class Event(TypedDict):
    kind: ReadOnly[str]
    payload: dict[str, object]

class Click(Event):
    kind: Literal["click"]     # OK: narrows a read-only key
    x: int
    y: int

class Broken(Event):
    payload: dict[str, int]    # error: payload is mutable

c: Click = {"kind": "click", "payload": {}, "x": 10, "y": 20}
print(c)
$ mypy app.py
app.py:13: error: Definition of field "payload" incompatible with base class "Event"  [misc]
Found 1 error in 1 file (checked 1 source file)

Typing **kwargs with Unpack

**kwargs: int means "every keyword argument is an int". When the keyword arguments have different types, that annotation doesn't help much (see Type hints for keyword arguments for the basics). Since Python 3.12 you can describe them with a TypedDict and Unpack:

from typing import NotRequired, TypedDict, Unpack

class RequestOptions(TypedDict):
    timeout: NotRequired[float]
    retries: NotRequired[int]
    headers: NotRequired[dict[str, str]]

def fetch(url: str, **kwargs: Unpack[RequestOptions]) -> None:
    timeout = kwargs.get("timeout", 10.0)
    retries = kwargs.get("retries", 3)
    print(f"GET {url} timeout={timeout} retries={retries} extra={kwargs}")

def fetch_json(url: str, **kwargs: Unpack[RequestOptions]) -> None:
    headers = {"Accept": "application/json", **kwargs.get("headers", {})}
    merged: RequestOptions = {**kwargs, "headers": headers}
    fetch(url, **merged)

fetch("https://example.com")
fetch("https://example.com", timeout=2.5)
opts: RequestOptions = {"retries": 0}
fetch("https://example.com", **opts)
fetch_json("https://example.com/api", retries=1)
GET https://example.com timeout=10.0 retries=3 extra={}
GET https://example.com timeout=2.5 retries=3 extra={'timeout': 2.5}
GET https://example.com timeout=10.0 retries=0 extra={'retries': 0}
GET https://example.com/api timeout=10.0 retries=1 extra={'retries': 1, 'headers': {'Accept': 'application/json'}}

Inside the function, kwargs has the type RequestOptions. At call sites, each keyword is checked against its own type, unknown keywords are rejected, and a RequestOptions dict can be passed with **:

from typing import NotRequired, TypedDict, Unpack

class RequestOptions(TypedDict):
    timeout: NotRequired[float]
    retries: NotRequired[int]

def fetch(url: str, **kwargs: Unpack[RequestOptions]) -> None:
    reveal_type(kwargs)

fetch("https://example.com", timeout="fast")
fetch("https://example.com", retry=2)
fetch("https://example.com", 2.5)
$ mypy app.py
app.py:8: note: Revealed type is "TypedDict(app.RequestOptions, {'timeout'?: float, 'retries'?: int})"
app.py:10: error: Argument "timeout" to "fetch" has incompatible type "str"; expected "float"  [arg-type]
app.py:11: error: Unexpected keyword argument "retry" for "fetch"  [call-arg]
app.py:12: error: Too many positional arguments for "fetch"  [call-arg]
Found 3 errors in 1 file (checked 1 source file)

This is most useful for wrappers that pass a shared set of options through several layers, where spelling out every keyword parameter in every function would be repetitive. Editors also show the individual keywords in completions and signature help. If the options have defaults that belong in the signature, ordinary keyword-only parameters (def fetch(url, *, timeout: float = 10.0)) are still clearer.

Two details:

No runtime checks

A TypedDict doesn't validate anything at runtime. isinstance() is not supported, and assigning the result of json.loads() (which returns Any) to a TypedDict variable is accepted by the checker no matter what the JSON contains:

import json
from typing import NotRequired, TypedDict

class User(TypedDict):
    id: int
    name: str
    email: NotRequired[str]

raw = '{"id": "42", "nmae": "Ann"}'
user: User = json.loads(raw)   # the checker trusts you: json.loads returns Any
print(user)

try:
    isinstance(user, User)
except TypeError as e:
    print("TypeError:", e)
{'id': '42', 'nmae': 'Ann'}
TypeError: TypedDict does not support instance and class checks

So for data that comes from outside your program (see JSON Module), validate it once at the boundary. The class keeps enough information to write a simple check yourself. get_type_hints() strips the ReadOnly/NotRequired wrappers unless you pass include_extras=True:

import json
from typing import NotRequired, ReadOnly, TypedDict, get_type_hints

class User(TypedDict):
    id: ReadOnly[int]
    name: str
    email: NotRequired[str]

print(get_type_hints(User))
print(get_type_hints(User, include_extras=True))

def check_keys(td: type, data: dict) -> list[str]:
    errors = []
    hints = get_type_hints(td)
    for key in sorted(td.__required_keys__ - data.keys()):
        errors.append(f"missing key {key!r}")
    for key in sorted(data.keys() - hints.keys()):
        errors.append(f"unknown key {key!r}")
    for key, tp in hints.items():
        if key in data and isinstance(tp, type) and not isinstance(data[key], tp):
            errors.append(f"{key!r} should be {tp.__name__}, got {type(data[key]).__name__}")
    return errors

print(check_keys(User, json.loads('{"id": 1, "name": "Ann"}')))
print(check_keys(User, json.loads('{"id": "42", "nmae": "Ann"}')))
{'id': <class 'int'>, 'name': <class 'str'>, 'email': <class 'str'>}
{'id': typing.ReadOnly[int], 'name': <class 'str'>, 'email': typing.NotRequired[str]}
[]
["missing key 'name'", "unknown key 'nmae'", "'id' should be int, got str"]

This only handles plain classes. For nested types like list[User] or str | None, use a library. pydantic validates TypedDicts directly with TypeAdapter (pydantic 2.14 shown, pip install pydantic):

from typing import NotRequired, TypedDict
from pydantic import TypeAdapter, ValidationError

class User(TypedDict):
    id: int
    name: str
    email: NotRequired[str]

users = TypeAdapter(list[User])

print(users.validate_json('[{"id": 1, "name": "Ann"}, {"id": "2", "name": "Bob", "email": "b@x.org"}]'))

try:
    users.validate_json('[{"id": "abc", "nmae": "Ann"}]')
except ValidationError as e:
    print(e)
[{'id': 1, 'name': 'Ann'}, {'id': 2, 'name': 'Bob', 'email': 'b@x.org'}]
2 validation errors for list[User]
0.id
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/int_parsing
0.name
  Field required [type=missing, input_value={'id': 'abc', 'nmae': 'Ann'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.14/v/missing

The result is still a list of plain dicts, typed as list[User]. pydantic converted "2" to 2 (its default lax mode) and ignored the unknown key nmae.

Closed TypedDicts and extra_items

A regular TypedDict is "open": a value of that type may contain more keys than declared, because a Point3D is a valid Point2D. That's why iterating over .values() gives you object, and why you can't assume there are no other keys. Literal dicts are still checked strictly, as shown at the start.

PEP 728 (Python 3.15, available now in typing_extensions) adds closed=True, which forbids extra keys, and extra_items=T, which allows extra keys whose values must all be of type T:

from typing_extensions import TypedDict

class Movie(TypedDict, closed=True):
    title: str
    year: int

class Tags(TypedDict, extra_items=str):
    name: str

m: Movie = {"title": "Alien", "year": 1979, "director": "Scott"}
t: Tags = {"name": "x", "color": "red", "size": 3}

def labels(tags: Tags) -> list[str]:
    return [f"{k}={v}" for k, v in tags.items()]

def years(movie: Movie) -> None:
    for value in movie.values():
        reveal_type(value)

print(labels({"name": "box", "color": "red"}))
$ pyright app.py
  app.py:10:45 - error: Type "dict[str, str | int]" is not assignable to declared type "Movie"
    Type "Literal['Scott']" is not assignable to item "extra_items"
      Type "Literal['Scott']" is not assignable to type "Never" (reportAssignmentType)
  app.py:11:49 - error: Type "dict[str, str | int]" is not assignable to declared type "Tags"
    "Literal[3]" is not assignable to "str" (reportAssignmentType)
  app.py:18:21 - information: Type of "value" is "str | int"
2 errors, 0 warnings, 1 information

Because Movie is closed, pyright knows its values are str | int. Pyright supports PEP 728 already; mypy 2.4 rejects extra_items and treats closed=True like a normal TypedDict. The keywords raise TypeError with typing.TypedDict on Python 3.14 and earlier, so import from typing_extensions until you require 3.15.

TypedDict or dataclass?

TypedDict dataclass
Runtime value plain dict instance of your class
Access d["key"] obj.attr
Methods, properties no yes
Optional fields missing keys (NotRequired) default values
Converting from/to JSON nothing to convert MyClass(**data) / asdict()
Runtime validation none none (use pydantic or attrs)

Use a TypedDict when the data is a dict and stays one: JSON you pass along, **kwargs, legacy code that already uses dicts, or libraries that require dicts. Use a dataclass when you own the data model and want behavior, defaults and attribute access.

Summary

Feature Since Meaning
class T(TypedDict) 3.8 dict with these keys and value types
TypedDict("T", {...}) 3.8 same, for keys that aren't identifiers
total=False 3.8 all keys of this class are optional
NotRequired[X] 3.11 this key may be missing
Required[X] 3.11 this key must be present, even with total=False
class T[V](TypedDict) 3.11 (Generic), 3.12 syntax generic TypedDict
**kwargs: Unpack[T] 3.12 each keyword argument has its own type
ReadOnly[X] 3.13 key can't be assigned or deleted through this type; allows covariant use
closed=True, extra_items=X 3.15 forbid extra keys, or constrain their values

Things to remember:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents