Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

TypedDict doesn’t define an instance of a dict. It defines a subtype of dict which has one (zero?) or more keys that must be present. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading