Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 562
jonathan.scholbach Avatar asked Oct 29 '25 04:10

jonathan.scholbach


1 Answers

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__
like image 56
jonathan.scholbach Avatar answered Oct 31 '25 19:10

jonathan.scholbach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!