将成员添加到Python枚举 [英] Adding members to Python Enums
问题描述
我知道这是不是标准用例,但是我需要在Python中动态添加一个 IntEnum
派生类的元素。请注意,使用功能API动态创建枚举是不够的。我需要添加元素到现有的枚举。我该怎么做?
I understand that this is NOT the standard use case, but I need to dynamically add elements to a IntEnum
derived class in Python. Notice that dynamically creating the Enum using the functional API is not enough. I need to add elements to an existing enum. How can I do this?
背景:对于那些你想知道为什么有人想这样做的人。我正在包装一个库,枚举的值在库中定义。我可以使用库API查询名称和值。但是我不能在初始化时执行,因为它依赖于根据用户请求由库动态加载的组件。我可以在启动时加载所有组件,并使用功能API在导入时创建枚举,但这是耗时且有副作用。
Background: For those of you wondering why would somebody want to do this. I am wrapping a library and the values for the enum are defined within the library. I can query the names and values using the library API. But I cannot do it upon initialization as it depends on components which are dynamically loaded by the library upon user request. I could load all components at start up and use the functional API to create the enum upon import but this is time consuming and has side effects.
推荐答案
枚举是不可变的,那就更重要了。您可以创建一个替换原来的新枚举:
Enums are immutable, that's rather the point. You can create a new enum that replaces the original instead:
from enum import Enum
names = [m.name for m in ExistingEnum] + ['newname1', 'newname2']
ExistingEnum = Enum('ExistingEnum', names)
,但任何现有的引用(例如其他模块)都将继续使用旧的定义。
but any existing references (say, in other modules) would continue to use the old definition.
名称
可以是:
- 包含成员名称的字符串,用空格或逗号分隔。值从
start
(可以设置为关键字参数并默认为1)递增1。 - 成员的可迭代名称(如上面的代码)。值从
开始
中递增1。 - (成员名称,值)对的可迭代。
- 成员名称 - >值对的映射。
- A string containing member names, separated either with spaces or commas. Values are incremented by 1 from
start
(which can be set as a keyword argument and defaults to 1). - An iterable of member names (as in the code above). Values are incremented by 1 from
start
. - An iterable of (member name, value) pairs.
- A mapping of member name -> value pairs.
这篇关于将成员添加到Python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!