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

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]

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 setup
comments 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?"