在Python中动态创建带有自定义值的枚举? [英] Dynamically create an enum with custom values in Python?

查看:276
本文介绍了在Python中动态创建带有自定义值的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时通过读取YAML文件中的值来创建枚举类型。所以我有这个:

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)

是否有适当的方法?我觉得调用 type 并不是一个很好的解决方案。

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

推荐答案

您可以使用 枚举功能性API

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

这篇关于在Python中动态创建带有自定义值的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆