Skip to content Skip to sidebar Skip to footer

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 Is there a way

Solution 1:

You'll need some extra code to support that use-case. I'll show it using aenum:

from aenum import IntEnum

classFruits(IntEnum):
    _init_ = 'value active'#
    apples = 0, True
    bananas = 1, False# deprecated
    pears = 2, False# deprecated
    strawberries = 3, True#    @classmethoddefactive(cls):
        return [m for m in cls if m.active]
    #    @classmethoddefdeprecated(cls):
        return [m for m in cls ifnot m.active]

and in use:

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

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).

Solution 2:

The answer is no, not with this setupcomments will not modify anything about your code and they are solely for user use.

Post a Comment for "How To Iterate Over Python Enum Ignoring "deprecated" Ones?"