Closed
Description
I want to know the Origin of an annotation. This works fine for basically everything, but there is no way to check if an annotation is a TypedDict subclass without resorting to (semantically) private API (by checking if it is an instance of _TypedDictMeta
), because issubclass(x, TypedDict)
fails. I believe this is because you don't want people thinking isinstance(x, TypedDict)
will work to actually validate the keys on a dict. However, I don't think there's any reason to prevent issubclass
on it
https://github.com/python/cpython/blob/1b4552c/Lib/typing.py#L1901
Here is an example use-case:
from typing import Dict, get_origin
def validate(data, annotation) -> bool:
"""check if `data` conforms to the type given in `annotation`"""
# this works
if get_origin(annotation) is Dict:
return isinstance(data, dict)
# but this doesn't...
elif is_a_typed_dict(annotation):
return isinstance(data, dict) and validate_typeddict_keys(data, annotation)
...
This could be solved in one of the following ways:
- allow
issubclass
onTypedDict
s- or allow it only on
TypedDict
itself and not subclasses of it, e.g. using a_root
classvar likeNamedTuple
does for its magic- although I see no reason not to allow it in that case either
- or allow it only on
- make
_TypedDictMeta
public API (rename toTypedDictMeta
) - make
get_origin
work onTypedDict
s (not ideal because it isn't really a type)
Metadata
Metadata
Assignees
Labels
No labels