Python 3.4.0 introduced enum
, I've read the doc but still don't know the usage of it. From my perspective, enum is an extended namedtuple
type, which may not be true. So these are what I want to know about enum:
- When and where to use enum?
- Why do we need enum? what are the advatages?
- What exactly is enum?
For example, the days of the week:
Enums are advantageous because they give a name to a constant, which makes code more readable; and because the individual members cannot be rebound, making Python Enums semi-constant (because the
Enum
itself could still be rebound).Besides more readable code, debugging is also easier as you see a name along with the value, not just the value
Desired behavior can be added to Enums
For example, as anyone who has worked with the datetime module knows,
datetime
anddate
have two different represntations for the days of the week: 0-6 or 1-7. Rather than keep track of that ourselves we can add a method to theWeekday
enum to extract the day from thedatetime
ordate
instance and return the matching enum member:Enum is a type, whose members are named constants, that all belong to (or should) a logical group of values. So far I have created
Enum
s for:FederalHoliday
is my most complex; it uses this recipe, and has methods to return the actual date the holiday takes place on for the year given, the next business day if the day in question is a holiday (or the range of days skipped includes the holiday or weekends), and the complete set of dates for a year. Here it is:Notes:
Date
is from my dbf packagethe enhanced
xrange
(supporting a range of dates) is also custom, but I don't think I have included it anywhere; I'll stuff it in mydbf
package next time I tinker with it.Disclosure: I am the author of the Python stdlib
Enum
, theenum34
backport, and the Advanced Enumeration (aenum
) library.PEP 435 ("Adding an Enum type to the Python standard library") behind the introduction of
Enum
in Python has a lot of examples of how the authors intended it to be used.More comments here.