Mariy
Mariy

Reputation: 5924

Subclassing typing.TypeDict

I skimmed over PEP-0589, and I am wondering why typing.TypedDict works when subclassing it like this:

class A(TypedDict, total=False):
    x: int
    y: int

Specifically, TypedDict is a function that exposes __mro_entries__, which is itself a function that returns a metaclass constructor. There are a few things that I don't understand:

  1. You can subclass a function? How does that work?
  2. How is the total kwarg provided to the TypedDict constructor?

I would really appreciate someone explaining this magic in detail and providing docs as I couldn't find it in the official docs.

Upvotes: 0

Views: 75

Answers (1)

chepner
chepner

Reputation: 532093

It's literally the __mro_entries__ provided by TypedDict that lets you inherit from it. From its documentation:

If a base that appears in a class definition is not an instance of type, then an __mro_entries__() method is searched on the base. If an mro_entries() method is found, the base is substituted with the result of a call to __mro_entries__() when creating the class.

I'm not sure of the exact mechanism, but TypedDict returns an instance of _TypedDictMeta, and _TypedDictMeta.__new__ accepts a keyword-only argument total.

Upvotes: 3

Related Questions