1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to define an alias value for an enum member?

Discussão em 'Python' iniciado por Stack, Novembro 28, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, an enum member carries an underlying value, which can be obtained by reading the value attribute. Conversely, an enum member can be obtained from its value by calling the enum type.

    class Food(enum.Enum):
    MEAT = 'meat'
    DAIRY = 'dairy'

    print(Food.MEAT.value) # 'meat'
    print(Food('meat') is Food.MEAT) # True


    I would like it to be possible to obtain the same enum member by passing several different values; obviously, only one of them would be canonical and obtainable from the value attribute. I can do it this way:

    class Food(enum.Enum):
    MEAT = 'meat'
    DAIRY = 'dairy'

    @classmethod
    def from_str(cls, item):
    match item:
    case 'spam'|'ham':
    return cls.MEAT
    case 'eggs'|'milk':
    return cls.DAIRY
    return cls(item)


    and then remember to keep using Food.from_str(s) instead of Food(s). This is workable, although I would rather have the aliases in the definition of the member instead of repeating members in a helper method (like in my other question involving Python enums). But there are also other problems with it:

    #!/usr/bin/env python3
    import argparse
    import enum

    class Food(enum.Enum):
    MEAT = 'meat'
    DAIRY = 'dairy'

    @classmethod
    def from_str(cls, item):
    match item:
    case 'spam'|'ham':
    return cls.MEAT
    case 'eggs'|'milk':
    return cls.DAIRY
    return cls(item)

    parser = argparse.ArgumentParser()
    parser.add_argument('food', type=Food.from_str)
    args = parser.parse_args()

    print(args.food)


    When I invoke this script with “bread” as the command-line argument, argparse complains about an “invalid from_str value”. So I would rather use type=Food as a add_argument argument, so that the type is identified correctly in the error message.

    How can this be solved?

    Continue reading...

Compartilhe esta Página