Flag枚举中所有值的表示

时间:2017-02-15 13:43:57

标签: python python-3.x enums python-3.6

我想要一个" ALL"我的python中的标志标志枚举

myenum.EVERY_MEMBER & myenum.ALL == myenum.EVERY_MEMBER

成立。我目前有:

from enum import Flag, auto

class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()
    .....

因为这个枚举可能会在任何开发状态下增长,所以我希望有类似

的东西
@property
def ALL(self):
    retval = self.NONE
    for member in self.__members__.values():
        retval |= member
    return retval

这不起作用:

RefreshFlags.EVENTS  & RefreshFlags.ALL

TypeError: unsupported operand type(s) for &: 'RefreshFlags' and 'property'

请注意,此问题目前仅与python 3.6或更高版本有关。

4 个答案:

答案 0 :(得分:9)

有几种方法可以解决这个问题:

使用类属性方法需要注意的一件事是,因为描述符是在类而不是元类上定义的,所以缺少对设置和删除的常规保护 - 换句话说:

>>> RefreshFlags.ALL
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

>>> RefreshFlags.ALL = 'oops'
>>> RefreshFlags.ALL
'oops'

创建新的基类:

# lightly tested
from enum import Flag, auto
from operator import or_ as _or_
from functools import reduce

class AllFlag(Flag):

    @classproperty
    def ALL(cls):
        cls_name = cls.__name__
        if not len(cls):
            raise AttributeError('empty %s does not have an ALL value' % cls_name)
        value = cls(reduce(_or_, cls))
        cls._member_map_['ALL'] = value
        return value

并在使用中:

class RefreshFlag(AllFlag):
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

>>> RefreshFlag.ALL
<RefreshFlag.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

ALL属性的有趣区别在于_member_map_中的名称设置 - 这允许为Enum成员提供相同的保护:

>>> RefreshFlag.ALL = 9
Traceback (most recent call last):
  ....
AttributeError: Cannot reassign members.

然而,这里存在竞争条件:如果RefreshFlag.ALL = ...RefreshFlag.ALL被激活之前发生,那么第一次被激活;出于这个原因,我会在这个实例中使用一个装饰器,因为装饰器会在它被破坏之前处理Enum。

# lightly tested

from enum import Flag, auto
from operator import or_ as _or_
from functools import reduce

def with_limits(enumeration):
    "add NONE and ALL psuedo-members to enumeration"
    none_mbr = enumeration(0)
    all_mbr = enumeration(reduce(_or_, enumeration))
    enumeration._member_map_['NONE'] = none_mbr
    enumeration._member_map_['ALL'] = all_mbr
    return enumeration

并在使用中:

@with_limits
class RefreshFlag(Flag):
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

>>> RefreshFlag.ALL = 99
Traceback (most recent call last):
  ...
AttributeError: Cannot reassign members.

>>> RefreshFlag.ALL 
<RefreshFlag.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

>>> RefreshFlag.NONE
<RefreshFlag.0: 0>

答案 1 :(得分:4)

TL; DR因为属性仅在类的实例上进行评估,而__members__只能在类上访问。

如果您在课程中访问property,则只返回property

>>> RefreshFlags.ALL
<property at 0x2a5d93382c8>

要使这项工作成功,你需要让它成为一种类方法:

from enum import Flag, auto

class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

    @classmethod
    def ALL(cls):
        retval = self.NONE
        for member in cls.__members__.values():
            retval |= member
        return retval

>>> RefreshFlags.ALL()
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

或访问实例上的属性:

from enum import Flag, auto

class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

    @property
    def ALL(self):
        retval = self.NONE
        # One needs to access .__class__ here!
        for member in self.__class__.__members__.values():
            retval |= member
        return retval

>>> RefreshFlags.EVENTS.ALL
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

在这两种情况下,您可以稍后进行比较:

>>> RefreshFlags.EVENTS & RefreshFlags.EVENTS.ALL
<RefreshFlags.EVENTS: 1>

您在评论中表示您希望ALL成员的行为与其他成员一样,在这种情况下,我建议使用类装饰器:

def with_ALL_member(enumeration):
    retval = enumeration(0)  # in case NONE is not defined
    for name, member in enumeration.__members__.items():
        retval |= member
    enumeration.ALL = retval
    return enumeration

@with_ALL_member
class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

>>> RefreshFlags.EVENTS & RefreshFlags.ALL
<RefreshFlags.EVENTS: 1>

>>> RefreshFlags.DEFENSES & RefreshFlags.ALL
<RefreshFlags.DEFENSES: 8>

类装饰器也可用于其他枚举:)

答案 2 :(得分:4)

跟进MSeifert的answer,可以编写一个@classproperty装饰器,允许您直接访问RefreshFlags.ALL作为属性(而不是传统方法或实例上的属性):

from enum import Flag, auto
from operator import or_
from functools import reduce


class classproperty:

    def __init__(self, func):
        self._func = func

    def __get__(self, obj, owner):
        return self._func(owner)


class RefreshFlags(Flag):

    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

    @classproperty
    def ALL(cls):
        return reduce(or_, cls)

您当然可以使用明确的ALL()循环编写for,如您的示例所示;以上仅作为替代方案提供。

>>> RefreshFlags.ALL
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>
>>> RefreshFlags.ALL & RefreshFlags.BUILDINGS
<RefreshFlags.BUILDINGS: 4>

答案 3 :(得分:0)

这是一个稍微紧凑的解决方案,使用更精简的描述符,使其更易于重用。

class _all:
    def __get__(self, instance, cls):
        return ~cls(0)


class RefreshFlags(Flag):
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

    ALL = _all()

RefreshFlags.ALL
>>> <RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

正如已经指出的那样,以这种方式定义的成员不会被包含在命名空间的 _member_map_ 字典中, 因此,它无法防止被覆盖。