Search code examples
pythonfilterenumsitems

How can I disable some item in python Enum, but not remove them


I have a enum OsTypeEnum:

class OsTypeEnum(Enum):
    WINDOWS = 100
    LINUX = 200
    MAC = 300
    ANDROID = 400
    IOS = 500

    @classmethod
    def get_list(cls):
        ret = []
        for e in cls:
           ret.append({'name': e.name, 'value': e.value})
        return ret

I need to hide ANDROID and IOS from calling the get_list function, but don't want to remove them from the OsTypeEnum.


Solution

  • Rather than hard-code the list of members to exclude, I would make that information part of each member instead. I'll show code using the aenum library1, but it can be done using the stdlib version, just more verbosely.

    from aenum import Enum
    
    class OsTypeEnum(Enum):
        #
        _init_ = 'value type'
        #
        WINDOWS = 100, 'pc'
        LINUX = 200, 'pc'
        MAC = 300, 'pc'
        ANDROID = 400, 'mobile'
        IOS = 500, 'mobile'
        #
        @classmethod
        def get_pc_list(cls):
            ret = []
            for e in cls:
                if e.type == 'pc':
                    ret.append({'name': e.name, 'value': e.value})
            return ret
        #
        @classmethod
        def get_mobile_list(cls):
            ret = []
            for e in cls:
                if e.type == 'mobile':
                    ret.append({'name': e.name, 'value': e.value})
            return ret
    

    By storing that extra piece of information on the member, you are more easily able to get your original list, plus other lists.

    In use, it looks like:

    >>> OsTypeEnum.get_pc_list()
    [{'name': 'WINDOWS', 'value': 100}, {'name': 'LINUX', 'value': 200}, {'name': 'MAC', 'value': 300}]
    
    >>> OsTypeEnum.get_mobile_list()
    [{'name': 'ANDROID', 'value': 400}, {'name': 'IOS', 'value': 500}]
    

    1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.