enum --- 对枚举的支持

3.4 新版功能.

源代码: Lib/enum.py


枚举是一组符号名称(枚举成员)的集合,枚举成员应该是唯一的、不可变的。在枚举中,可以对成员进行恒等比较,并且枚举本身是可迭代的。

模块内容

此模块定义了四个枚举类,它们可被用来定义名称和值的不重复集合: Enum, IntEnum, FlagIntFlag。 此外还定义了一个装饰器 unique() 和一个辅助类 auto

class enum.Enum

此基类用于创建枚举常量。 请参阅 Functional API 小节了解另一种替代性的构建语法。

class enum.IntEnum

此基类用于创建属于 int 的子类的枚举常量。

class enum.IntFlag

此基类用于创建可使用按位运算符进行组合而不会丢失其 IntFlag 成员资格的枚举常量。 IntFlag 成员同样也是 int 的子类。

class enum.Flag

此基类用于创建枚举常量 可使用按位运算符进行组合而不会丢失其 Flag 成员资格的枚举常量。

enum.unique()

此 Enum 类装饰器可确保只将一个名称绑定到任意一个值。

class enum.auto

实例会被替换为一个可用作 Enum 成员的正确值。

3.6 新版功能: Flag, IntFlag, auto

创建一个 Enum

枚举是使用 class 语法来创建的,这使得它们易于读写。 另一种替代创建方法的描述见 Functional API。 要定义一个枚举,可以对 Enum 进行如下的子类化:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...

注解

Enum 的成员值

成员值可以为任意类型: int, str 等等。 如果具体的值不重要,你可以使用 auto 实例,将为你选择适当的值。 但如果你混用 auto 与其他值则需要小心谨慎。

注解

命名法

  • Color 是一个 枚举 (或称 enum)

  • 属性 Color.RED, Color.GREEN 等等是 枚举成员 (或称 enum 成员) 并且被用作常量。

  • 枚举成员具有 名称 (Color.RED 的名称为 REDColor.BLUE 的值为 3 等等。)

注解

虽然我们使用 class 语法来创建 Enum,但 Enum 并不是普通的 Python 类。 更多细节请参阅 How are Enums different?

枚举成员具有适合人类阅读的表示形式:

>>> print(Color.RED)
Color.RED

...而它们的 repr 包含更多信息:

>>> print(repr(Color.RED))
<Color.RED: 1>

一个枚举成员的 type 就是它所从属的枚举:

>>> type(Color.RED)
<enum 'Color'>
>>> isinstance(Color.GREEN, Color)
True
>>>

Enum 的成员还有一个包含其条目名称的特征属性:

>>> print(Color.RED.name)
RED

枚举支持按照定义顺序进行迭代:

>>> class Shake(Enum):
...     VANILLA = 7
...     CHOCOLATE = 4
...     COOKIES = 9
...     MINT = 3
...
>>> for shake in Shake:
...     print(shake)
...
Shake.VANILLA
Shake.CHOCOLATE
Shake.COOKIES
Shake.MINT

枚举成员是可哈希的,因此它们可在字典和集合中可用:

>>> apples = {}
>>> apples[Color.RED] = 'red delicious'
>>> apples[Color.GREEN] = 'granny smith'
>>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
True

对枚举成员及其属性的程序化访问

有时对枚举中的成员进行程序化访问是很有用的(例如在某些场合不能使用 Color.RED 因为在编程时并不知道要指定的确切颜色)。 Enum 允许这样的访问:

>>> Color(1)
<Color.RED: 1>
>>> Color(3)
<Color.BLUE: 3>

如果你希望通过 name 来访问枚举成员,可使用条目访问:

>>> Color['RED']
<Color.RED: 1>
>>> Color['GREEN']
<Color.GREEN: 2>

如果你有一个枚举成员并且需要它的 namevalue:

>>> member = Color.RED
>>> member.name
'RED'
>>> member.value
1

复制枚举成员和值

不允许有同名的枚举成员:

>>> class Shape(Enum):
...     SQUARE = 2
...     SQUARE = 3
...
Traceback (most recent call last):
...
TypeError: Attempted to reuse key: 'SQUARE'

但是,允许两个枚举成员有相同的值。 假定两个成员 A 和 B 有相同的值(且 A 先被定义),则 B 就是 A 的一个别名。 按值查找 A 和 B 的值将返回 A。 按名称查找 B 也将返回 A:

>>> class Shape(Enum):
...     SQUARE = 2
...     DIAMOND = 1
...     CIRCLE = 3
...     ALIAS_FOR_SQUARE = 2
...
>>> Shape.SQUARE
<Shape.SQUARE: 2>
>>> Shape.ALIAS_FOR_SQUARE
<Shape.SQUARE: 2>
>>> Shape(2)
<Shape.SQUARE: 2>

注解

试图创建具有与某个已定义的属性(另一个成员或方法等)相同名称的成员或者试图创建具有相同名称的属性也是不允许的。

确保唯一的枚举值

默认情况下,枚举允许有多个名称作为某个相同值的别名。 如果不想要这样的行为,可以使用以下装饰器来确保每个值在枚举中只被使用一次:

@enum.unique

专用于枚举的 class 装饰器。 它会搜索一个枚举的 __members__ 并收集所找到的任何别名;只要找到任何别名就会引发 ValueError 并附带相关细节信息:

>>> from enum import Enum, unique
>>> @unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE

使用自动设定的值

如果确切的值不重要,你可以使用 auto:

>>> from enum import Enum, auto
>>> class Color(Enum):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

值将由 _generate_next_value_() 来选择,该函数可以被重载:

>>> class AutoName(Enum):
...     def _generate_next_value_(name, start, count, last_values):
...         return name
...
>>> class Ordinal(AutoName):
...     NORTH = auto()
...     SOUTH = auto()
...     EAST = auto()
...     WEST = auto()
...
>>> list(Ordinal)
[<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]

注解

默认 _generate_next_value_() 方法的目标是提供所给出的最后一个 int 所在序列的下一个 int,但这种行为方式属于实现细节并且可能发生改变。

迭代

对枚举成员的迭代不会给出别名:

>>> list(Shape)
[<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]

特殊属性 __members__ 是一个从名称到成员的只读有序映射。 它包含枚举中定义的所有名称,包括别名:

>>> for name, member in Shape.__members__.items():
...     name, member
...
('SQUARE', <Shape.SQUARE: 2>)
('DIAMOND', <Shape.DIAMOND: 1>)
('CIRCLE', <Shape.CIRCLE: 3>)
('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)

__members__ 属性可被用于对枚举成员进行详细的程序化访问。 例如,找出所有别名:

>>> [name for name, member in Shape.__members__.items() if member.name != name]
['ALIAS_FOR_SQUARE']

比较

枚举成员是按标识号进行比较的:

>>> Color.RED is Color.RED
True
>>> Color.RED is Color.BLUE
False
>>> Color.RED is not Color.BLUE
True

枚举值之间的排序比较 不被 支持。 Enum 成员不属于整数 (另请参阅下文的 IntEnum):

>>> Color.RED < Color.BLUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Color' and 'Color'

相等比较的定义如下:

>>> Color.BLUE == Color.RED
False
>>> Color.BLUE != Color.RED
True
>>> Color.BLUE == Color.BLUE
True

与非枚举值的比较将总是不相等(同样地,IntEnum 被显式设计成不同的行为,参见下文):

>>> Color.BLUE == 2
False

允许的枚举成员和属性

以上示例使用整数作为枚举值。 使用整数相当简洁方便(并由 Functional API 默认提供),但并不强制要求使用。 在大部分用例中,开发者都关心枚举的实际值是什么。 但如果值 确实 重要,则枚举可以使用任意的值。

枚举属于 Python 的类,并可具有普通方法和特殊方法。 如果我们有这样一个枚举:

>>> class Mood(Enum):
...     FUNKY = 1
...     HAPPY = 3
...
...     def describe(self):
...         # self is the member here
...         return self.name, self.value
...
...     def __str__(self):
...         return 'my custom str! {0}'.format(self.value)
...
...     @classmethod
...     def favorite_mood(cls):
...         # cls here is the enumeration
...         return cls.HAPPY
...

那么:

>>> Mood.favorite_mood()
<Mood.HAPPY: 3>
>>> Mood.HAPPY.describe()
('HAPPY', 3)
>>> str(Mood.FUNKY)
'my custom str! 1'

对于允许内容的规则如下:以单下划线开头和结尾的名称是由枚举保留而不可使用;在枚举中定义的所有其他属性将成为该枚举的成员,例外项则包括特殊方法成员 (__str__(), __add__() 等),描述符 (方法也属于描述符) 以及在 _ignore_ 中列出的变量名。

注意:如果你的枚举定义了 __new__() 和/或 __init__() 那么指定给枚举成员的任何值都会被传入这些方法。 请参阅示例 Planet

受限的 Enum 子类化

一个新的 Enum 类必须基于一个 Enum 类,至多一个实体数据类型以及出于实际需要的任意多个基于 object 的 mixin 类。 这些基类的顺序为:

class EnumName([mix-in, ...,] [data-type,] base-enum):
    pass

另外,仅当一个枚举未定义任何成员时才允许子类化该枚举。 因此禁止这样的写法:

>>> class MoreColor(Color):
...     PINK = 17
...
Traceback (most recent call last):
...
TypeError: Cannot extend enumerations

但是允许这样的写法:

>>> class Foo(Enum):
...     def some_behavior(self):
...         pass
...
>>> class Bar(Foo):
...     HAPPY = 1
...     SAD = 2
...

允许子类化定义了成员的枚举将会导致违反类型与实例的某些重要的不可变规则。 在另一方面,允许在一组枚举之间共享某些通用行为也是有意义的。 (请参阅示例 OrderedEnum 。)

封存

枚举可以被封存与解封:

>>> from test.test_enum import Fruit
>>> from pickle import dumps, loads
>>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
True

封存的常规限制同样适用:可封存枚举必须在模块的最高层级中定义,因为解封操作要求它们可以从该模块导入。

注解

使用 pickle 协议版本 4 可以方便地封存嵌套在其他类中的枚举。

通过在枚举类中定义 __reduce_ex__() 可以对 Enum 成员的封存/解封方式进行修改。

功能性 API

Enum 类属于可调用对象,它提供了以下功能性 API:

>>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
>>> Animal
<enum 'Animal'>
>>> Animal.ANT
<Animal.ANT: 1>
>>> Animal.ANT.value
1
>>> list(Animal)
[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]

该 API 的主义类似于 namedtuple。 调用 Enum 的第一个参数是枚举的名称。

第二个参数是枚举成员名称的 来源。 它可以是一个用空格分隔的名称字符串、名称序列、键/值对 2 元组的序列,或者名称到值的映射(例如字典)。 最后两种选项使得可以为枚举任意赋值;其他选项会自动以从 1 开始递增的整数赋值(使用 start 形参可指定不同的起始值)。 返回值是一个派生自 Enum 的新类。 换句话说,以上对 Animal 的赋值就等价于:

>>> class Animal(Enum):
...     ANT = 1
...     BEE = 2
...     CAT = 3
...     DOG = 4
...

默认以 1 而以 0 作为起始数值的原因在于 0 的布尔值为 False,但所有枚举成员都应被求值为 True

封存通过功能性 API 创建的枚举可能会有点麻烦,因为要使用帧堆栈的实现细节来尝试并找出枚举是在哪个模块中创建的(例如,当你使用不同模块的工具函数时可能会失败,在 IronPython 或 Jython 上也可能会没有效果)。 解决办法是显式地指定模块名称,如下所示:

>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)

警告

如果未提供 module,且 Enum 无法确定是哪个模块,新的 Enum 成员将不可被解封;为了让错误尽量靠近源头,封存将被禁用。

新的 pickle 协议版本 4 在某些情况下同样依赖于 __qualname__ 被设为特定位置以便 pickle 能够找到相应的类。 例如,类是否存在于全局作用域的 SomeData 类中:

>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')

完整的签名为:

Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)

将被新 Enum 类将记录为其名称的数据。

名称

Enum 的成员。 这可以是一个空格或逗号分隔的字符串 (起始值将为 1,除非另行指定):

'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'

或是一个名称的迭代器:

['RED', 'GREEN', 'BLUE']

或是一个 (名称, 值) 对的迭代器:

[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]

或是一个映射:

{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}
模块

新 Enum 类所在模块的名称。

qualname

新 Enum 类在模块中的具体位置。

类型

要加入新 Enum 类的类型。

start

当只传入名称时要使用的起始数值。

在 3.5 版更改: 增加了 start 形参。

派生的枚举

IntEnum

The first variation of Enum that is provided is also a subclass of int. Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:

>>> from enum import IntEnum
>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Request(IntEnum):
...     POST = 1
...     GET = 2
...
>>> Shape == 1
False
>>> Shape.CIRCLE == 1
True
>>> Shape.CIRCLE == Request.POST
True

However, they still can't be compared to standard Enum enumerations:

>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...
>>> Shape.CIRCLE == Color.RED
False

IntEnum values behave like integers in other ways you'd expect:

>>> int(Shape.CIRCLE)
1
>>> ['a', 'b', 'c'][Shape.CIRCLE]
'b'
>>> [i for i in range(Shape.SQUARE)]
[0, 1]

IntFlag

The next variation of Enum provided, IntFlag, is also based on int. The difference being IntFlag members can be combined using the bitwise operators (&, |, ^, ~) and the result is still an IntFlag member. However, as the name implies, IntFlag members also subclass int and can be used wherever an int is used. Any operation on an IntFlag member besides the bit-wise operations will lose the IntFlag membership.

3.6 新版功能.

Sample IntFlag class:

>>> from enum import IntFlag
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...
>>> Perm.R | Perm.W
<Perm.R|W: 6>
>>> Perm.R + Perm.W
6
>>> RW = Perm.R | Perm.W
>>> Perm.R in RW
True

It is also possible to name the combinations:

>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...     RWX = 7
>>> Perm.RWX
<Perm.RWX: 7>
>>> ~Perm.RWX
<Perm.-8: -8>

Another important difference between IntFlag and Enum is that if no flags are set (the value is 0), its boolean evaluation is False:

>>> Perm.R & Perm.X
<Perm.0: 0>
>>> bool(Perm.R & Perm.X)
False

Because IntFlag members are also subclasses of int they can be combined with them:

>>> Perm.X | 8
<Perm.8|X: 9>

标志

The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int. While it is possible to specify the values directly it is recommended to use auto as the value and let Flag select an appropriate value.

3.6 新版功能.

Like IntFlag, if a combination of Flag members results in no flags being set, the boolean evaluation is False:

>>> from enum import Flag, auto
>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.RED & Color.GREEN
<Color.0: 0>
>>> bool(Color.RED & Color.GREEN)
False

Individual flags should have values that are powers of two (1, 2, 4, 8, ...), while combinations of flags won't:

>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...     WHITE = RED | BLUE | GREEN
...
>>> Color.WHITE
<Color.WHITE: 7>

Giving a name to the "no flags set" condition does not change its boolean value:

>>> class Color(Flag):
...     BLACK = 0
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.BLACK
<Color.BLACK: 0>
>>> bool(Color.BLACK)
False

注解

For the majority of new code, Enum and Flag are strongly recommended, since IntEnum and IntFlag break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). IntEnum and IntFlag should be used only in cases where Enum and Flag will not do; for example, when integer constants are replaced with enumerations, or for interoperability with other systems.

Others

While IntEnum is part of the enum module, it would be very simple to implement independently:

class IntEnum(int, Enum):
    pass

This demonstrates how similar derived enumerations can be defined; for example a StrEnum that mixes in str instead of int.

Some rules:

  1. When subclassing Enum, mix-in types must appear before Enum itself in the sequence of bases, as in the IntEnum example above.

  2. While Enum can have members of any type, once you mix in an additional type, all the members must have values of that type, e.g. int above. This restriction does not apply to mix-ins which only add methods and don't specify another data type such as int or str.

  3. When another data type is mixed in, the value attribute is not the same as the enum member itself, although it is equivalent and will compare equal.

  4. %-style formatting: %s and %r call the Enum class's __str__() and __repr__() respectively; other codes (such as %i or %h for IntEnum) treat the enum member as its mixed-in type.

  5. Formatted string literals, str.format(), and format() will use the mixed-in type's __format__(). If the Enum class's str() or repr() is desired, use the !s or !r format codes.

When to use __new__() vs. __init__()

__new__() must be used whenever you want to customize the actual value of the Enum member. Any other modifications may go in either __new__() or __init__(), with __init__() being preferred.

For example, if you want to pass several items to the constructor, but only want one of them to be the value:

>>> class Coordinate(bytes, Enum):
...     """
...     Coordinate with binary codes that can be indexed by the int code.
...     """
...     def __new__(cls, value, label, unit):
...         obj = bytes.__new__(cls, [value])
...         obj._value_ = value
...         obj.label = label
...         obj.unit = unit
...         return obj
...     PX = (0, 'P.X', 'km')
...     PY = (1, 'P.Y', 'km')
...     VX = (2, 'V.X', 'km/s')
...     VY = (3, 'V.Y', 'km/s')
...

>>> print(Coordinate['PY'])
Coordinate.PY

>>> print(Coordinate(3))
Coordinate.VY

Interesting examples

While Enum, IntEnum, IntFlag, and Flag are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one's own.

Omitting values

In many use-cases one doesn't care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration:

  • use instances of auto for the value

  • use instances of object as the value

  • use a descriptive string as the value

  • use a tuple as the value and a custom __new__() to replace the tuple with an int value

Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members.

Whichever method you choose, you should provide a repr() that also hides the (unimportant) value:

>>> class NoValue(Enum):
...     def __repr__(self):
...         return '<%s.%s>' % (self.__class__.__name__, self.name)
...

Using auto

Using auto would look like:

>>> class Color(NoValue):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.GREEN
<Color.GREEN>

Using object

Using object would look like:

>>> class Color(NoValue):
...     RED = object()
...     GREEN = object()
...     BLUE = object()
...
>>> Color.GREEN
<Color.GREEN>

Using a descriptive string

Using a string as the value would look like:

>>> class Color(NoValue):
...     RED = 'stop'
...     GREEN = 'go'
...     BLUE = 'too fast!'
...
>>> Color.GREEN
<Color.GREEN>
>>> Color.GREEN.value
'go'

Using a custom __new__()

Using an auto-numbering __new__() would look like:

>>> class AutoNumber(NoValue):
...     def __new__(cls):
...         value = len(cls.__members__) + 1
...         obj = object.__new__(cls)
...         obj._value_ = value
...         return obj
...
>>> class Color(AutoNumber):
...     RED = ()
...     GREEN = ()
...     BLUE = ()
...
>>> Color.GREEN
<Color.GREEN>
>>> Color.GREEN.value
2

注解

The __new__() method, if defined, is used during creation of the Enum members; it is then replaced by Enum's __new__() which is used after class creation for lookup of existing members.

OrderedEnum

An ordered enumeration that is not based on IntEnum and so maintains the normal Enum invariants (such as not being comparable to other enumerations):

>>> class OrderedEnum(Enum):
...     def __ge__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value >= other.value
...         return NotImplemented
...     def __gt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value > other.value
...         return NotImplemented
...     def __le__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value <= other.value
...         return NotImplemented
...     def __lt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value < other.value
...         return NotImplemented
...
>>> class Grade(OrderedEnum):
...     A = 5
...     B = 4
...     C = 3
...     D = 2
...     F = 1
...
>>> Grade.C < Grade.A
True

DuplicateFreeEnum

Raises an error if a duplicate member name is found instead of creating an alias:

>>> class DuplicateFreeEnum(Enum):
...     def __init__(self, *args):
...         cls = self.__class__
...         if any(self.value == e.value for e in cls):
...             a = self.name
...             e = cls(self.value).name
...             raise ValueError(
...                 "aliases not allowed in DuplicateFreeEnum:  %r --> %r"
...                 % (a, e))
...
>>> class Color(DuplicateFreeEnum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...     GRENE = 2
...
Traceback (most recent call last):
...
ValueError: aliases not allowed in DuplicateFreeEnum:  'GRENE' --> 'GREEN'

注解

This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. If the only desired change is disallowing aliases, the unique() decorator can be used instead.

Planet

If __new__() or __init__() is defined the value of the enum member will be passed to those methods:

>>> class Planet(Enum):
...     MERCURY = (3.303e+23, 2.4397e6)
...     VENUS   = (4.869e+24, 6.0518e6)
...     EARTH   = (5.976e+24, 6.37814e6)
...     MARS    = (6.421e+23, 3.3972e6)
...     JUPITER = (1.9e+27,   7.1492e7)
...     SATURN  = (5.688e+26, 6.0268e7)
...     URANUS  = (8.686e+25, 2.5559e7)
...     NEPTUNE = (1.024e+26, 2.4746e7)
...     def __init__(self, mass, radius):
...         self.mass = mass       # in kilograms
...         self.radius = radius   # in meters
...     @property
...     def surface_gravity(self):
...         # universal gravitational constant  (m3 kg-1 s-2)
...         G = 6.67300E-11
...         return G * self.mass / (self.radius * self.radius)
...
>>> Planet.EARTH.value
(5.976e+24, 6378140.0)
>>> Planet.EARTH.surface_gravity
9.802652743337129

TimePeriod

An example to show the _ignore_ attribute in use:

>>> from datetime import timedelta
>>> class Period(timedelta, Enum):
...     "different lengths of time"
...     _ignore_ = 'Period i'
...     Period = vars()
...     for i in range(367):
...         Period['day_%d' % i] = i
...
>>> list(Period)[:2]
[<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
>>> list(Period)[-2:]
[<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]

How are Enums different?

Enums have a custom metaclass that affects many aspects of both derived Enum classes and their instances (members).

Enum Classes

The EnumMeta metaclass is responsible for providing the __contains__(), __dir__(), __iter__() and other methods that allow one to do things with an Enum class that fail on a typical class, such as list(Color) or some_enum_var in Color. EnumMeta is responsible for ensuring that various other methods on the final Enum class are correct (such as __new__(), __getnewargs__(), __str__() and __repr__()).

Enum Members (aka instances)

The most interesting thing about Enum members is that they are singletons. EnumMeta creates them all while it is creating the Enum class itself, and then puts a custom __new__() in place to ensure that no new ones are ever instantiated by returning only the existing member instances.

Finer Points

Supported __dunder__ names

__members__ is a read-only ordered mapping of member_name:member items. It is only available on the class.

__new__(), if specified, must create and return the enum members; it is also a very good idea to set the member's _value_ appropriately. Once all the members are created it is no longer used.

Supported _sunder_ names

  • _name_ -- name of the member

  • _value_ -- value of the member; can be set / modified in __new__

  • _missing_ -- a lookup function used when a value is not found; may be overridden

  • _ignore_ -- a list of names, either as a list() or a str(), that will not be transformed into members, and will be removed from the final class

  • _order_ -- used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation)

  • _generate_next_value_ -- used by the Functional API and by auto to get an appropriate value for an enum member; may be overridden

3.6 新版功能: _missing_, _order_, _generate_next_value_

3.7 新版功能: _ignore_

To help keep Python 2 / Python 3 code in sync an _order_ attribute can be provided. It will be checked against the actual order of the enumeration and raise an error if the two do not match:

>>> class Color(Enum):
...     _order_ = 'RED GREEN BLUE'
...     RED = 1
...     BLUE = 3
...     GREEN = 2
...
Traceback (most recent call last):
...
TypeError: member order does not match _order_

注解

In Python 2 code the _order_ attribute is necessary as definition order is lost before it can be recorded.

Enum member type

Enum members are instances of their Enum class, and are normally accessed as EnumClass.member. Under certain circumstances they can also be accessed as EnumClass.member.member, but you should never do this as that lookup may fail or, worse, return something besides the Enum member you are looking for (this is another good reason to use all-uppercase names for members):

>>> class FieldTypes(Enum):
...     name = 0
...     value = 1
...     size = 2
...
>>> FieldTypes.value.size
<FieldTypes.size: 2>
>>> FieldTypes.size.value
2

在 3.5 版更改.

Boolean value of Enum classes and members

Enum members that are mixed with non-Enum types (such as int, str, etc.) are evaluated according to the mixed-in type's rules; otherwise, all members evaluate as True. To make your own Enum's boolean evaluation depend on the member's value add the following to your class:

def __bool__(self):
    return bool(self.value)

Enum classes always evaluate as True.

Enum classes with methods

If you give your Enum subclass extra methods, like the Planet class above, those methods will show up in a dir() of the member, but not of the class:

>>> dir(Planet)
['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
>>> dir(Planet.EARTH)
['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']

Combining members of Flag

If a combination of Flag members is not named, the repr() will include all named flags and all named combinations of flags that are in the value:

>>> class Color(Flag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...     MAGENTA = RED | BLUE
...     YELLOW = RED | GREEN
...     CYAN = GREEN | BLUE
...
>>> Color(3)  # named combination
<Color.YELLOW: 3>
>>> Color(7)      # not named combination
<Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>