Thanks to visit codestin.com
Credit goes to github.com

Skip to content

No (public) way to dynamically introspect if an annotation is a TypedDict #751

Closed
@pxeger

Description

@pxeger

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 on TypedDicts
    • or allow it only on TypedDict itself and not subclasses of it, e.g. using a _root classvar like NamedTuple does for its magic
      • although I see no reason not to allow it in that case either
  • make _TypedDictMeta public API (rename to TypedDictMeta)
  • make get_origin work on TypedDicts (not ideal because it isn't really a type)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions