I'm trying to make a TypedDict subclass that returns None if a key would cause a KeyError and that key is a part of the TypedDict's annotations as Optional. I realize this isn't quite possible, since TypedDict can't be subclassed except to define annotations. Is there any other eloquent way to do this?
Here's what I'm trying to do:
from typing import TypedDict, get_args, get_origin
class FilledTypedDict(TypedDict):
def __getitem__(self, k):
if k in self.__annotations__:
annotation = self.__annotations__[k]
if get_origin(annotation) is Union and type(None) in get_args(annotation):
return None
return super().__getitem__(k)
This gives me a TypedDict classes can contain only type annotations. How do I work my way around that?