Search code examples
pythonpython-typing

Understanding a subclass of "TypedDict" with just one field defined


Despite reading the TypedDict documentation and numerous examples, I can't understand the code-snippet below. I'm definitely missing something (a concept).

MyClass specifies one field (messages), but shouldn't it have at least two? For key and value? What is the key and value in this case?

from typing import Annotated
from typing_extensions import TypedDict

class MyClass(TypedDict):
    messages: Annotated[list, add_messages]
    # messages have the type "list".
    # "add_messages" is some function that appends
    # rather than overwrites messages to list.

Solution

  • TypedDict doesn't define an instance of a dict. It defines a subtype of dict which has zero or more keys that must be present. (Zero is allowed, but in most cases you'll specify at least one.) There are no values, only type(s) for whatever values are in an instance.

    For example, {'messages': [1,2,3]} is an instance of MyClass. {'foo': [1,2,3]} is not (because MyClass doesn't define a key foo), nor is {'messages': [1,2,3], 'foo': 3} (because MyClass defines only messages as a key, not any additional keys).

    That is, messages itself is the (one and only) key that any instance of MyClass must have. Any such instance can have any value associated with messages, as long as that value has type list.

    • {'messages': []}
    • {'messages': [1]}
    • {'messages': [1,2,3,10]}
    • etc

    are all instances of MyClass.

    If there were two fields, then any instance would need to have both keys present with appropriate values. For example,

    class Foo(TypedDict):
        bar: int
        baz: float
    

    would have instances like {'bar': 3, 'baz': 3.14159}: both bar and baz must be present (with appropriately typed values), and no other keys are allowed.