Getting keys defined in TypedDict in order with type information

Is there a way to get keys defined in TypedDict in order? Is it also possible to do so retaining the Literal keys information?

Example:

class PersonDetail(TypedDict, total=True):
    name: ReadOnly[str]
    age: ReadOnly[int]
    occupation: ReadOnly[str]

HEADER = ("name", "age", "occupation")

def write_csv(details: dict[str, PersonDetail], outpath: Path):
    with outpath.open("w") as op:
        writer = csv.DictWriter(op, HEADER)
        writer.writeheader()
        for position, detail in details.items():
            do_something_with_position(position)
            writer.writerow(detail)

I would like to eliminate the extra HEADER definition. I want a method/function/attribute like the following:

reveal_type(magic_func(PersonDetail)) # tuple[Literal["name"], Literal["age"], Literal["occupation"]]

Is there a way to do this? It seems like it should be possible given the nature of TypedDicts.

You can get the keys defined in order using inspect.get_annotations:

from typing import TypedDict
import inspect

class Foo(TypedDict):
    bar: int
    baz: str

print(tuple(inspect.get_annotations(Foo).keys()))

produces ('bar', 'baz'), but I don’t think it’s possible to get these typed Literal unfortunately.

1 Like

Ah, nice! I thought about this, but I thought I saw something about __extra__ key annotation in PEP 728, and thought that would get in the way. But now I see __extra__ is not going to be used as a special key. So this works. I don’t think __extra_items__ would be part of annotations.

OTOH, it seems something like TypedDict.__known_keys__ could be added, which would return the keys in a tuple with type information intact.