'TypedDict when keys have invalid names

If I have a key in a dictionary with an invalid identifier, such as A(2). How can I create a TypedDict with this field?

E.g

from typing import TypedDict

class RandomAlphabet(TypedDict):
    A(2): str

is not valid Python code, resulting in the error:

SyntaxError: illegal target for annotation

The same problem is with reserved keywords:

class RandomAlphabet(TypedDict):
    return: str

throws:

SyntaxError: invalid syntax


Solution 1:[1]

This is fairly messy, but it works if you need inheritance.

class RandomAlphabet(
    TypedDict(
        "RandomAlphabet",
        {"A(2)": str, "return": str},
    ),
    SomeInheritedTypedDict,
):
    pass

You can also replace pass with other normal properties that don't use invalid identifiers or reserved keywords if you have any.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grant Gryczan