pythondictionarytype-hintingpython-typing

Python get keys from unbound TypedDict


I would like to get the keys from an unbound TypedDict subclass.

What is the correct way to do so?

Below I have a hacky method, and I'm wondering if there's a more standard way.


Current Method

I used inspect.getmembers on the TypedDict subclass, and saw the __annotations__ attribute houses a mapping of the keys + type annotations. From there, I use .keys() to get access to all of the keys.

from typing_extensions import TypedDict


class SomeTypedDict(TypedDict):

    key1: str
    key2: int


print(SomeTypedDict.__annotations__.keys())

Prints: dict_keys(['key1', 'key2'])

This does work, but I am wondering, is there a better/more standard way?


Versions

python==3.6.5
typing-extensions==3.7.4.2

Solution

  • The code documentation explicitly states (referring to a sample derived class Point2D):

    The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.

    So if the modules code says this, there is no reason to look for another method.

    Note that your method only printed the names of the dictionary keys. You can get the names and the type simply by accessing the full dictionary:

    print(SomeTypedDict.__annotations__)
    

    Which will get you back all the info:

    {'key1': <class 'str'>, 'key2': <class 'int'>}