创新互联Python教程:EnumHOWTO

Enum HOWTO

An Enum is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful repr(), grouping, type-safety, and a few other features.

They are most useful when you have a variable that can take one of a limited selection of values. For example, the days of the week:

 
 
 
 
  1. >>> from enum import Enum
  2. >>> class Weekday(Enum):
  3. ... MONDAY = 1
  4. ... TUESDAY = 2
  5. ... WEDNESDAY = 3
  6. ... THURSDAY = 4
  7. ... FRIDAY = 5
  8. ... SATURDAY = 6
  9. ... SUNDAY = 7

Or perhaps the RGB primary colors:

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

As you can see, creating an Enum is as simple as writing a class that inherits from Enum itself.

备注

Case of Enum Members

Because Enums are used to represent constants we recommend using UPPER_CASE names for members, and will be using that style in our examples.

Depending on the nature of the enum a member’s value may or may not be important, but either way that value can be used to get the corresponding member:

 
 
 
 
  1. >>> Weekday(3)

As you can see, the repr() of a member shows the enum name, the member name, and the value. The str() of a member shows only the enum name and member name:

 
 
 
 
  1. >>> print(Weekday.THURSDAY)
  2. Weekday.THURSDAY

The type of an enumeration member is the enum it belongs to:

 
 
 
 
  1. >>> type(Weekday.MONDAY)
  2. >>> isinstance(Weekday.FRIDAY, Weekday)
  3. True

Enum members have an attribute that contains just their name:

 
 
 
 
  1. >>> print(Weekday.TUESDAY.name)
  2. TUESDAY

Likewise, they have an attribute for their value:

 
 
 
 
  1. >>> Weekday.WEDNESDAY.value
  2. 3

Unlike many languages that treat enumerations solely as name/value pairs, python Enums can have behavior added. For example, datetime.date has two methods for returning the weekday: weekday() and isoweekday(). The difference is that one of them counts from 0-6 and the other from 1-7. Rather than keep track of that ourselves we can add a method to the Weekday enum to extract the day from the date instance and return the matching enum member:

 
 
 
 
  1. @classmethod
  2. def from_date(cls, date):
  3. return cls(date.isoweekday())

The complete Weekday enum now looks like this:

 
 
 
 
  1. >>> class Weekday(Enum):
  2. ... MONDAY = 1
  3. ... TUESDAY = 2
  4. ... WEDNESDAY = 3
  5. ... THURSDAY = 4
  6. ... FRIDAY = 5
  7. ... SATURDAY = 6
  8. ... SUNDAY = 7
  9. ... #
  10. ... @classmethod
  11. ... def from_date(cls, date):
  12. ... return cls(date.isoweekday())

Now we can find out what today is! Observe:

 
 
 
 
  1. >>> from datetime import date
  2. >>> Weekday.from_date(date.today())

Of course, if you’re reading this on some other day, you’ll see that day instead.

This Weekday enum is great if our variable only needs one day, but what if we need several? Maybe we’re writing a function to plot chores during a week, and don’t want to use a list — we could use a different type of Enum:

 
 
 
 
  1. >>> from enum import Flag
  2. >>> class Weekday(Flag):
  3. ... MONDAY = 1
  4. ... TUESDAY = 2
  5. ... WEDNESDAY = 4
  6. ... THURSDAY = 8
  7. ... FRIDAY = 16
  8. ... SATURDAY = 32
  9. ... SUNDAY = 64

We’ve changed two things: we’re inherited from Flag, and the values are all powers of 2.

Just like the original Weekday enum above, we can have a single selection:

 
 
 
 
  1. >>> first_week_day = Weekday.MONDAY
  2. >>> first_week_day

But Flag also allows us to combine several members into a single variable:

 
 
 
 
  1. >>> weekend = Weekday.SATURDAY | Weekday.SUNDAY
  2. >>> weekend

You can even iterate over a Flag variable:

 
 
 
 
  1. >>> for day in weekend:
  2. ... print(day)
  3. Weekday.SATURDAY
  4. Weekday.SUNDAY

Okay, let’s get some chores set up:

 
 
 
 
  1. >>> chores_for_ethan = {
  2. ... 'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday.FRIDAY,
  3. ... 'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY,
  4. ... 'answer SO questions': Weekday.SATURDAY,
  5. ... }

And a function to display the chores for a given day:

 
 
 
 
  1. >>> def show_chores(chores, day):
  2. ... for chore, days in chores.items():
  3. ... if day in days:
  4. ... print(chore)
  5. >>> show_chores(chores_for_ethan, Weekday.SATURDAY)
  6. answer SO questions

In cases where the actual values of the members do not matter, you can save yourself some work and use auto() for the values:

 
 
 
 
  1. >>> from enum import auto
  2. >>> class Weekday(Flag):
  3. ... MONDAY = auto()
  4. ... TUESDAY = auto()
  5. ... WEDNESDAY = auto()
  6. ... THURSDAY = auto()
  7. ... FRIDAY = auto()
  8. ... SATURDAY = auto()
  9. ... SUNDAY = auto()

Programmatic access to enumeration members and their attributes

Sometimes it’s useful to access members in enumerations programmatically (i.e. situations where Color.RED won’t do because the exact color is not known at program-writing time). Enum allows such access:

 
 
 
 
  1. >>> Color(1)
  2. >>> Color(3)

If you want to access enum members by name, use item access:

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

If you have an enum member and need its name or value:

 
 
 
 
  1. >>> member = Color.RED
  2. >>> member.name
  3. 'RED'
  4. >>> member.value
  5. 1

Duplicating enum members and values

Having two enum members with the same name is invalid:

 
 
 
 
  1. >>> class Shape(Enum):
  2. ... SQUARE = 2
  3. ... SQUARE = 3
  4. ...
  5. Traceback (most recent call last):
  6. ...
  7. TypeError: 'SQUARE' already defined as 2

However, an enum member can have other names associated with it. Given two entries A and B with the same value (and A defined first), B is an alias for the member A. By-value lookup of the value of A will return the member A. By-name lookup of A will return the member A. By-name lookup of B will also return the member A:

 
 
 
 
  1. >>> class Shape(Enum):
  2. ... SQUARE = 2
  3. ... DIAMOND = 1
  4. ... CIRCLE = 3
  5. ... ALIAS_FOR_SQUARE = 2
  6. ...
  7. >>> Shape.SQUARE
  8. >>> Shape.ALIAS_FOR_SQUARE
  9. >>> Shape(2)

备注

Attempting to create a member with the same name as an already defined attribute (another member, a method, etc.) or attempting to create an attribute with the same name as a member is not allowed.

Ensuring unique enumeration values

By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, you can use the unique() decorator:

 
 
 
 
  1. >>> from enum import Enum, unique
  2. >>> @unique
  3. ... class Mistake(Enum):
  4. ... ONE = 1
  5. ... TWO = 2
  6. ... THREE = 3
  7. ... FOUR = 3
  8. ...
  9. Traceback (most recent call last):
  10. ...
  11. ValueError: duplicate values found in : FOUR -> THREE

Using automatic values

If the exact value is unimportant you can use auto:

 
 
 
 
  1. >>> from enum import Enum, auto
  2. >>> class Color(Enum):
  3. ... RED = auto()
  4. ... BLUE = auto()
  5. ... GREEN = auto()
  6. ...
  7. >>> [member.value for member in Color]
  8. [1, 2, 3]

The values are chosen by _generate_next_value_(), which can be overridden:

 
 
 
 
  1. >>> class AutoName(Enum):
  2. ... def _generate_next_value_(name, start, count, last_values):
  3. ... return name
  4. ...
  5. >>> class Ordinal(AutoName):
  6. ... NORTH = auto()
  7. ... SOUTH = auto()
  8. ... EAST = auto()
  9. ... WEST = auto()
  10. ...
  11. >>> [member.value for member in Ordinal]
  12. ['NORTH', 'SOUTH', 'EAST', 'WEST']

备注

The _generate_next_value_() method must be defined before any members.

Iteration

Iterating over the members of an enum does not provide the aliases:

 
 
 
 
  1. >>> list(Shape)
  2. [, , ]

The special attribute __members__ is a read-only ordered mapping of names to members. It includes all names defined in the enumeration, including the aliases:

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

The __members__ attribute can be used for detailed programmatic access to the enumeration members. For example, finding all the aliases:

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

Comparisons

Enumeration members are compared by identity:

 
 
 
 
  1. >>> Color.RED is Color.RED
  2. True
  3. >>> Color.RED is Color.BLUE
  4. False
  5. >>> Color.RED is not Color.BLUE
  6. True

Ordered comparisons between enumeration values are not supported. Enum members are not integers (but see IntEnum below):

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

Equality comparisons are defined though:

 
 
 
 
  1. >>> Color.BLUE == Color.RED
  2. False
  3. >>> Color.BLUE != Color.RED
  4. True
  5. >>> Color.BLUE == Color.BLUE
  6. True

Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently, see below):

 
 
 
 
  1. >>> Color.BLUE == 2
  2. False

Allowed members and attributes of enumerations

Most of the examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value is important, enumerations can have arbitrary values.

Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration:

 
 
 
 
  1. >>> class Mood(Enum):
  2. ... FUNKY = 1
  3. ... HAPPY = 3
  4. ...
  5. ... def describe(self):
  6. ... # self is the member here
  7. ... return self.name, self.value
  8. ...
  9. ... def __str__(self):
  10. ... return 'my custom str! {0}'.format(self.value)
  11. ...
  12. ... @classmethod
  13. ... def favorite_mood(cls):
  14. ... # cls here is the enumeration
  15. ... return cls.HAPPY
  16. ...

Then:

 
 
 
 
  1. >>> Mood.favorite_mood()
  2. >>> Mood.HAPPY.describe()
  3. ('HAPPY', 3)
  4. >>> str(Mood.FUNKY)
  5. 'my custom str! 1'

The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (__str__(), __add__(), etc.), descriptors (methods are also descriptors), and variable names listed in _ignore_.

Note: if your enumeration defines __new__() and/or __init__() then any value(s) given to the enum member will be passed into those methods. See Planet for an example.

Restricted Enum subclassing

A new Enum class must have one base enum class, up to one concrete data type, and as many object-based mixin classes as needed. The order of these base classes is:

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

Also, subclassing an enumeration is allowed only if the enumeration does not define any members. So this is forbidden:

 
 
 
 
  1. >>> class MoreColor(Color):
  2. ... PINK = 17
  3. ...
  4. Traceback (most recent call last):
  5. ...
  6. TypeError: cannot extend

But this is allowed:

 
 
 
 
  1. >>> class Foo(Enum):
  2. ... def some_behavior(self):
  3. ... pass
  4. ...
  5. >>> class Bar(Foo):
  6. ... HAPPY = 1
  7. ... SAD = 2
  8. ...

Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See OrderedEnum for an example.)

Pickling

Enumerations can be pickled and unpickled:

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

The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module.

备注

With pickle protocol version 4 it is possible to easily pickle enums nested in other classes.

It is possible to modify how enum members are pickled/unpickled by defining __reduce_ex__() in the enumeration class.

Functional API

The Enum class is callable, providing the following functional API:

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

The semantics of this API resemble namedtuple. The first argument of the call to Enum is the name of the enumeration.

The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. The last two options enable assigning arbitrary values to enumerations; the others auto-assign increasing integers starting with 1 (use the start parameter to specify a different starting value). A new class derived from Enum is returned. In other words, the above assignment to Animal is equivalent to:

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

The reason for defaulting to 1 as the starting number and not 0 is that 0 is False in a boolean sense, but by default enum members all evaluate to True.

Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in a separate module, and also may not work on IronPython or Jython). The solution is to specify the module name explicitly as follows:

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

警告

If module is not supplied, and Enum cannot determine what it is, the new Enum members will not be unpicklable; to keep errors closer to the source, pickling will be disabled.

The new pickle protocol 4 also, in some circumstances, relies on __qualname__ being set to the location where pickle will be able to find the class. For example, if the class was made available in class SomeData in the global scope:

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

The complete signature is:

 
 
 
 
  1. Enum(
  2. value='NewEnumName',
  3. names=<...>,
  4. *,
  5. module='...',
  6. qualname='...',
  7. type=,
  8. start=1,
  9. )

value

What the new enum class will record as its name.

names

The enum members. This can be a whitespace- or comma-separated string (values will start at 1 unless otherwise specified):

 
 
 
 
  1. 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'

or an iterator of names:

 
 
 
 
  1. ['RED', 'GREEN', 'BLUE']

or an iterator of (name, value) pairs:

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

or a mapping:

 
 
 
 
  1. {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}

module

name of module where new enum class can be found.

qualname

where in module new enum class can be found.

type

type to mix in to new enum class.

start

number to start counting at if only names are passed in.

在 3.5 版更改: The start parameter was added.

Derived Enumerations

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:

 
 
 
 
  1. >>> from enum import IntEnum
  2. >>> class Shape(IntEnum):
  3. ... CIRCLE = 1
  4. ... SQUARE = 2
  5. ...
  6. >>> class Request(IntEnum):
  7. ... POST = 1
  8. ... GET = 2
  9. ...
  10. >>> Shape == 1
  11. False
  12. >>> Shape.CIRCLE == 1
  13. True
  14. >>> Shape.CIRCLE == Request.POST
  15. True

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

 
 
 
 
  1. >>> class Shape(IntEnum):
  2. ... CIRCLE = 1
  3. ... SQUARE = 2
  4. ...
  5. >>> class Color(Enum):
  6. ... RED = 1
  7. ... GREEN = 2
  8. ...
  9. >>> Shape.CIRCLE == Color.RED
  10. False

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

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

StrEnum

The second variation of Enum that is provided is also a subclass of str. Members of a StrEnum can be compared to strings; by extension, string enumerations of different types can also be compared to each other.

3.11 新版功能.

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, if possible. Like IntEnum, IntFlag members are also integers 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.

Bit-wise operations that result in invalid IntFlag values will lose the IntFlag membership. See FlagBoundary for details.

3.6 新版功能.

在 3.11 版更改.

Sample IntFlag class:

 
 
 
 
  1. >>> from enum import IntFlag
  2. >>> class Perm(IntFlag):
  3. ... R = 4
  4. ... W = 2
  5. ... X = 1
  6. ...
  7. >>> Perm.R | Perm.W
  8. >>> Perm.R + Perm.W
  9. 6
  10. >>> RW = Perm.R | Perm.W
  11. >>> Perm.R in RW
  12. True

It is also possible to name the combinations:

 
 
 
 
  1. >>> class Perm(IntFlag):
  2. ... R = 4
  3. ... W = 2
  4. ... X = 1
  5. ... RWX = 7
  6. >>> Perm.RWX
  7. >>> ~Perm.RWX
  8. >>> Perm(7)

备注

Named combinations are considered aliases. Aliases do not show up during iteration, but can be returned from by-value lookups.

在 3.11 版更改.

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

 
 
 
 
  1. >>> Perm.R & Perm.X
  2. >>> bool(Perm.R & Perm.X)
  3. False

Because IntFlag members are also subclasses of int they can be combined with them (but may lose IntFlag membership:

 
 
 
 
  1. >>> Perm.X | 4
  2. >>> Perm.X | 8
  3. 9

备注

The negation operator, ~, always returns an IntFlag member with a positive value:

 
 
 
 
  1. >>> (~Perm.X).value == (Perm.R|Perm.W).value == 6
  2. True

IntFlag members can also be iterated over:

 
 
 
 
  1. >>> list(RW)
  2. [, ]

3.11 新版功能.

Flag

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:

 
 
 
 
  1. >>> from enum import Flag, auto
  2. >>> class Color(Flag):
  3. ... RED = auto()
  4. ... BLUE = auto()
  5. ... GREEN = auto()
  6. ...
  7. >>> Color.RED & Color.GREEN
  8. >>> bool(Color.RED & Color.GREEN)
  9. False

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

 
 
 
 
  1. >>> class Color(Flag):
  2. ... RED = auto()
  3. ... BLUE = auto()
  4. ... GREEN = auto()
  5. ... WHITE = RED | BLUE | GREEN
  6. ...
  7. >>> Color.WHITE

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

 
 
 
 
  1. >>> class Color(Flag):
  2. ... BLACK = 0
  3. ... RED = auto()
  4. ... BLUE = auto()
  5. ... GREEN = auto()
  6. ...
  7. >>> Color.BLACK
  8. >>> bool(Color.BLACK)
  9. False

Flag members can also be iterated over:

 
 
 
 
  1. >>> purple = Color.RED | Color.BLUE
  2. >>> list(purple)
  3. [, ]

3.11 新版功能.

备注

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:

 
 
 
 
  1. class IntEnum(int, Enum):
  2. pass

This demonstrates how similar derived enumerations can be defined; for example a FloatEnum that mixes in float 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. Mix-in typ

    网站标题:创新互联Python教程:EnumHOWTO
    文章网址:http://www.shufengxianlan.com/qtweb/news11/426811.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联