Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create an enum with custom values in Python? [duplicate]

Tags:

python

enums

I would like to create an enum type at runtime by reading the values in a YAML file. So I have this:

# Fetch the values v = {'foo':42, 'bar':24}  # Create the enum e = type('Enum', (), v) 

Is there a proper way to do it? I feel calling type is not a very neat solution.

like image 674
nowox Avatar asked Nov 13 '15 10:11

nowox


People also ask

Can enum have two same values python?

By definition, the enumeration member values are unique. However, you can create different member names with the same values.

Can we create dynamic enum?

You can dynamically create source code by reading from the database and simply outputting the results in a format conducive to building an enum. However, it is impractical to create an enum at run time.

What is enum Auto ()?

Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes. Example #1 : In this example we can see that by using enum. auto() method, we are able to assign the numerical values automatically to the class attributes by using this method.

Can two enum values be the same?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.


Video Answer


1 Answers

You can create new enum type using Enum functional API:

In [1]: import enum  In [2]: DynamicEnum = enum.Enum('DynamicEnum', {'foo':42, 'bar':24})  In [3]: type(DynamicEnum) Out[3]: enum.EnumMeta  In [4]: DynamicEnum.foo Out[4]: <DynamicEnum.foo: 42>  In [5]: DynamicEnum.bar Out[5]: <DynamicEnum.bar: 24>  In [6]: list(DynamicEnum) Out[6]: [<DynamicEnum.foo: 42>, <DynamicEnum.bar: 24>] 
like image 79
awesoon Avatar answered Sep 19 '22 23:09

awesoon