Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a TypedDict class with keys containing hyphens [duplicate]

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"]]
like image 255
Evyn Avatar asked Jan 27 '26 23:01

Evyn


1 Answers

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

like image 70
Paweł Rubin Avatar answered Jan 29 '26 12:01

Paweł Rubin



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!