PEP 814: Add frozendict built-in type

Yes, we’ll have to think about how this new builtin type (if it is accepted) interacts with TypedDict. (“We” here doesn’t necessarily mean the authors of PEP 814; this is something we can add separately later.)

Currently, TypedDict is specified as being restricted to instances of exactly dict: no subclasses, no other kinds of Mappings. So if we don’t change anything, frozendicts would not be compatible with TypedDict at all.

A few options:

  1. Add class TD(TypedDict, frozen=True): (as Thomas suggests). I assume this would mean that it is like TypedDict, except it must be a frozendict instead of a dict. But probably lots of people will want to write APIs that can accept either a dict or a frozendict, not just one of the two. Another variant could be that dict is acceptable for frozen=True, but not the reverse. This makes some sense because dict mostly only adds functionality to frozendict. Except hashing.
  2. Add some more general kind of TypedMapping that can contain any kind of Mapping with fixed keys. This has been suggested before but I don’t know if there’s been a design that is fully fleshed out.
  3. Add some type qualifier like Frozen[MyTypedDict] that indicates a transformation of an existing TypedDict into a frozen one. Then naturally, MyTypedDict | Frozen[MyTypedDict] means you accept a dict in either thawing state.

We could also wait and see how widely adopted frozendict is going to be before we add type system support. This might create a bit of a chicken-and-egg problem though; people may be hesitant to start using it if they can’t use it with TypedDict.

8 Likes