Dynamically create an enum with custom values in Python?

孤街醉人 提交于 2020-07-06 05:27:21

问题


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.


回答1:


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>]


来源:https://stackoverflow.com/questions/33690064/dynamically-create-an-enum-with-custom-values-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!