[Python] How to associate a literal label with a type and extract it to define another type in...

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to associate a string label with each class and then use those labels to define a Literal type for validation or type checking purposes. Here’s a simplified example of what I’m trying to do:

    from typing import Literal

    class Apple:
    label = "apple"

    class Mango:
    label = "mango"

    # I'd like to define this type using the class labels above:
    type FruitName = Literal[Apple.label, Mango.label]


    This doesn’t work because Literal expects constant string values at type-check time, but Apple.label and Mango.label are not treated as constants.

    Mypy error: Parameter 1 of Literal[...] is invalid [valid-type]

    Continue reading...

Compartilhe esta Página