Python动态枚举
我想在从SQL表中加载的Python中创建动态枚举。 SQL的输出将是tuplets的列表,我想填写枚举的属性。
假设我收到此列表:
lst = [('PROCESS_0', 0, "value", 123, False), ('PROCESS_1',1,"anothervalue", 456, True)]
我现在想填写以下枚举中的值:
class Jobs(IntEnum):
def __new__(cls, value: int, label: str, heartbeat: int = 60, heartbeat_required: bool = False):
obj = int.__new__(cls, value)
obj._value_ = value
obj.label = label
obj.heartbeat = heartbeat
obj.heartbeat_required = heartbeat_required
return obj
元组中的第一个变量应该是枚举的变量名称,我已经对此进行了解决:
locals()['Test'] = (0, '', 789, False)
但是这仅适用于单个值,似乎我无法在枚举内运行循环。当使用这样的循环时:
for i in lst:
locals()[i[0]] = (i[1], i[2], i[3])
python发送此错误 typeError:尝试重复使用密钥:'i'',它可能来自只有常数的枚举。
有没有(可能是优雅的)解决方案?
非常感谢!
I would like to create dynamic enums in python loaded from a SQL Table. The output of SQL will be a list of tuplets, which with I want to fill the attributes of the enum.
Lets say I receive this list:
lst = [('PROCESS_0', 0, "value", 123, False), ('PROCESS_1',1,"anothervalue", 456, True)]
I now want to fill the values in the enum below:
class Jobs(IntEnum):
def __new__(cls, value: int, label: str, heartbeat: int = 60, heartbeat_required: bool = False):
obj = int.__new__(cls, value)
obj._value_ = value
obj.label = label
obj.heartbeat = heartbeat
obj.heartbeat_required = heartbeat_required
return obj
The first variable in the tuple should be the variable name of the enum, I have solved this with:
locals()['Test'] = (0, '', 789, False)
But this only works for single values, it seems that I can not run a for loop within enum. When using a for loop like this:
for i in lst:
locals()[i[0]] = (i[1], i[2], i[3])
Python sends this error TypeError: Attempted to reuse key: 'i' which propably comes from enums only having constants.
Is there any (possibly elegant) solution for this?
Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
_ignore_ =“ I”
。像:You need to use
_ignore_ = "i"
. Something like:在 https://docs.pypython.org/3/howto/ enum.html#timeperiod
请注意,
_ignore _
可以避免使用ofiper
ecipt.__ _____ ,可以避免使用dict Gracements。Check the example at https://docs.python.org/3/howto/enum.html#timeperiod
Note that the
_ignore_
can be avoided in favor of dict comprehensionThen you can access all possible enum values via
Period.__members__