How can I create a TypedDict class that supports keys containing hyphens or other characters that are supported in strings, such as "justify-content" in the example below.
from typing import TypedDict, Literal
from typing_extensions import NotRequired
class Attributes(TypedDict):
width: NotRequired[str]
height: NotRequired[str]
direction: NotRequired[Literal["row", "column"]]
justify-content: NotRequired[Literal["start", "end", "center", "equally-spaced"]]
It is possible with the functional syntax:
from typing import TypedDict, Literal
from typing_extensions import NotRequired
Attributes = TypedDict(
"Attributes",
{
"width": NotRequired[
str,
],
"height": NotRequired[
str,
],
"direction": NotRequired[
Literal["row", "column"],
],
"justify-content": NotRequired[
Literal["start", "end", "center", "equally-spaced"]
],
},
)
It's mentioned in the documentation
The functional syntax should also be used when any of the keys are not valid identifiers, for example because they are keywords or contain hyphens
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With