如何遍历Python枚举,而忽略“不推荐使用"的枚举.那些? [英] How to iterate over Python enum ignoring "deprecated" ones?
问题描述
如果我设置了这样的枚举类
If I have an enum class set up like this
class fruits(enum.IntEnum):
apples = 0
bananas = 1 # deprecated
pears = 2 # deprecated
strawberries = 3
是否有一种方法可以动态获取未弃用的枚举(基本上只获取苹果和草莓?它们仅通过注释进行标记,而我不希望创建一组弃用的" notifs
Is there a way to dynamically get the enum's that are not deprecated (basically only fetch apples and strawberries? They're only marked via comment, and I prefer not to create a set of "deprecated" notifs
推荐答案
您将需要一些额外的代码来支持该用例.我将使用 aenum
1 :
You'll need some extra code to support that use-case. I'll show it using aenum
1:
from aenum import IntEnum
class Fruits(IntEnum):
_init_ = 'value active'
#
apples = 0, True
bananas = 1, False # deprecated
pears = 2, False # deprecated
strawberries = 3, True
#
@classmethod
def active(cls):
return [m for m in cls if m.active]
#
@classmethod
def deprecated(cls):
return [m for m in cls if not m.active]
并在使用中:
>>> list(Fruits)
[<Fruits.apples: 0>, <Fruits.bananas: 1>, <Fruits.pears: 2>, <Fruits.strawberries: 3>]
>>> Fruits.apples
<Fruits.apples: 0>
>>> Fruits.bananas
<Fruits.bananas: 1>
>>> Fruits.active()
[<Fruits.apples: 0>, <Fruits.strawberries: 3>]
>>> Fruits.deprecated()
[<Fruits.bananas: 1>, <Fruits.pears: 2>]
1 披露:我是 Python的作者stdlib Enum
, enum34
反向端口和高级枚举( aenum
)库(stdlib enum
的替代品).
1 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library (a drop-in replacement for the stdlib enum
).
这篇关于如何遍历Python枚举,而忽略“不推荐使用"的枚举.那些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!