Convert an enum to a list in Python

Viewed 12936

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"?

3 Answers

Python's Enum object has build-in enumerable.name and enumerable.value attributes for each member of an Enum.

an_enum = Enum('AnEnum', {'first': 1, 'second': 2})


[el.value for el in an_enum]
# returns: [1, 2]

[el.name for el in an_enum]
# returns: ['first', 'second']

Sidenode: Be careful with assert. If someone runs your script with python -O asserts will never fail.

To check if a value is part of an enum:

if 1 in [el.value for el in an_enum]:
    pass

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'

I'm not sure why you're defining enums like you do, there's supported functional way to do this:

en_enum = Enum('Numbers', {'first': 1, 'second': 2})

If this suits your needs, you can do

>>> en_enum(1)
<Numbers.first: 1>

>>> en_enum(3)
ValueError: 3 is not a valid Numbers

not actually membership check, but you don't need any special methods/transformers

Related