Python dynamic enum



我想在python中创建从SQL表加载的动态枚举。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)

但这只适用于单个值,似乎我不能在enum内运行for循环。当使用这样的for循环时:

for i in lst:
locals()[i[0]] = (i[1], i[2], i[3])

Python发送此错误TypeError: attempt to reuse key: 'i'这可能是因为枚举只有常量。

是否有任何(可能是优雅的)解决方案?

提前感谢!

您需要使用_ignore_ = "i"。比如:

class Jobs(IntEnum):
_ignore_ = "i"
def __new__(cls, value, label, heartbeat=60, heartbeat_required=False):
obj = int.__new__(cls, value)
obj._value_ = value
obj.label = label
obj.heartbeat = heartbeat
obj.heartbeat_required = heartbeat_required
return obj
for i in lst:
locals()[i[0]] = i[1:]

在https://docs.python.org/3/howto/enum.html#timeperiod查看示例

注意,可以避免_ignore_以支持字典理解

from datetime import timedelta
class Period(timedelta, Enum):
"different lengths of time"
vars().update({ f"day_{i}": i for i in range(367) })

那么你可以通过Period.__members__

访问所有可能的enum值

最新更新