[Python] Is there a more elegant rewrite for this Python Enum value_of implementation?

Discussão em 'Python' iniciado por Stack, Dezembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I would like to get a value_of implementation for the StrEnum (Python 3.9.x). For example:

    from enum import Enum


    class StrEnum(str, Enum):
    """Enum with str values"""
    pass

    class BaseStrEnum(StrEnum):
    """Base Enum"""
    @classmethod
    def value_of(cls, value):
    try:
    return cls[value]
    except KeyError:
    try:
    return cls(value)
    except ValueError:
    return None


    and then can use it like this:

    class Fruits(BaseStrEnum):
    BANANA = "Banana"
    PEA = "Pea"
    APPLE = "Apple"

    print(Fruits.value_of('BANANA'))
    print(Fruits.value_of('Banana'))


    it is just that the nested try-except doesn't look amazing, is there a better more idiomatic rewrite?

    Continue reading...

Compartilhe esta Página