Search code examples
pythonenumsassert

Convert an enum to a list in Python


I have an enum that I define like this:

def make_enum(**enums):
    return type('Enum', (), enums)

an_enum = make_enum(first=1, second=2)

At some later point I would like to check, if a value that I took as a parameter in a funciton is part of an_enum. Usually i would do it like this

assert 1 in to_list(an_enum)

How can I convert the enum object an_enum to a list? If that is not possible, how can I check if a value "is part of the enum"?


Solution

  • How can I convert the enum object an_enum to a list?

    >>> [name for name in dir(an_enum) if not name.startswith('_')]
    ['first', 'second']
    

    How can I check if a value "is part of the enum"?

    >>> getattr(an_enum, 'first')
    1
    >>> getattr(an_enum, '1')
    Traceback [...] 
    AttributeError: type object 'Enum' has no attribute '1'