pythonpython-3.xdictionarytypingcode-inspection

Python typing: Retrieve required keys from TypedDict definition


In Python3.10, I have a typing.TypedDict definition and want to programmatically retrieve which keys are required. How can I inspect the type definition in order to get the required keys?


Solution

  • Taking PEP-655 into account, there are different scenarios: The whole TypedDict could have total=False or total=True, and individual fields could be marked as either Required or NotRequired. And there could also be the edge case where a TypedDict is inheriting from another, and one of them has total=False and the other one has total=True. In order to handle this edge case, Python introduced the __required_keys__ attribute on the TypedDict. This is what we have to look at:

    from typing import Any, _TypedDictMeta
    
    
    def required_keys(type_: _TypedDictMeta) -> frozenset[str]:
        return type_.__required_keys__