`typing.Never` and `TypedDict`

:wave: Was skimming Typed dictionaries — typing documentation and saw the following (in the “Update method” docs):

class B(TypedDict):
    x: NotRequired[typing.Never]
    y: ReadOnly[int]

This sparks two questions:

  1. Since total defaults to True, what’s the usefulness of x: NotRequired[typing.Never] as opposed to just… not mentioning key x? (I’d naively expect something like total=True implying “all possible key names are inherently NotRequired[typing.Never]”.
  2. Since this is the only use of typing.Never in the TypedDict docs, should the spec spell out what the expectation is around typing.Never in a TypedDict?

Intuitively, I’d expect this to imply “Extra keys are OK, except for x. That’s a banned key”.

class B(TypedDict, total=False):
    x: typing.Never
    y: int

which, if that’s true, that’s probably something worth spelling out so it isn’t left to interpretation.

Because TypedDicts are a structural type, a value of type B can have any other keys at runtime. But we say that key x is of type Never, which is a type that has no inhabitants, which means that the key cannot exist. I’m not sure how practically useful this is, but I think all this behavior follows logically from other parts of the spec, so there’s no need to mention it explicitly.

1 Like

I think this would be impossible to instantiate. Without the NotRequired marking, you’d be required to have an x key of type Never, which is impossible.

This leaves the interpretation of x: NotRequired[typing.Never] as “any key is allowed, except x

1 Like

… Yup. There it is… Wow I’m quite embarrassed that it had to be spelled out that plainly for me to get it.

All right, pack it in.

Edit: wait nevermind, see Typed dictionaries — typing documentation

It’s not impossible to instantiate because it has total=False, meaning that any key may be omitted.

2 Likes

The documentation for this is obscure.

The docs.python.org TypeDict documentation make no mention of typing.Never and the Required/NotRequired section of typing.readthedocs.org doesn’t mention it either. That “NotRequired” can be used to prohibit a key is a bit of an oxymoron.