Saturday, 28 October 2023

Runtime checking for extra keys in TypedDict

This answer tells how to validated a TypedDict at runtime, but it won't catch the case of an extra key being present.

For example, this doesn't throw. How can I make it throw?

from typing import Any, TypeVar

from pydantic import TypeAdapter
from typing_extensions import TypedDict

T = TypeVar('T')

def runtime_check_typed_dict(TypedDictClass: type[T], object_: Any) -> T:
    TypedDictValidator = TypeAdapter(TypedDictClass)
    return TypedDictValidator.validate_python(object_, strict=True)


class MyThing(TypedDict):
    key: str

obj_: Any = {'key': 'stuff', 'extra': 'this should throw!'}

runtime_check_typed_dict(MyThing, obj_)


from Runtime checking for extra keys in TypedDict

No comments:

Post a Comment