Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 354 – Enumerations in Python

Author:
Ben Finney <ben+python at benfinney.id.au>
Status:
Superseded
Type:
Standards Track
Created:
20-Dec-2005
Python-Version:
2.6
Post-History:
20-Dec-2005
Superseded-By:
435

Table of Contents

Rejection Notice

This PEP has been rejected. This doesn’t slot nicely into any of theexisting modules (like collections), and the Python standard libraryeschews having lots of individual data structures in their ownmodules. Also, the PEP has generated no widespread interest. Forthose who need enumerations, there are cookbook recipes and PyPIpackages that meet these needs.

Note: this PEP was superseded byPEP 435,which has been accepted inMay 2013.

Abstract

This PEP specifies an enumeration data type for Python.

An enumeration is an exclusive set of symbolic names bound toarbitrary unique values. Values within an enumeration can be iteratedand compared, but the values have no inherent relationship to valuesoutside the enumeration.

Motivation

The properties of an enumeration are useful for defining an immutable,related set of constant values that have a defined sequence but noinherent semantic meaning. Classic examples are days of the week(Sunday through Saturday) and school assessment grades (‘A’ through‘D’, and ‘F’). Other examples include error status values and stateswithin a defined process.

It is possible to simply define a sequence of values of some otherbasic type, such asint orstr, to represent discretearbitrary values. However, an enumeration ensures that such valuesare distinct from any others, and that operations without meaning(“Wednesday times two”) are not defined for these values.

Specification

An enumerated type is created from a sequence of arguments to thetype’s constructor:

>>>Weekdays=enum('sun','mon','tue','wed','thu','fri','sat')>>>Grades=enum('A','B','C','D','F')

Enumerations with no values are meaningless. The exceptionEnumEmptyError is raised if the constructor is called with novalue arguments.

The values are bound to attributes of the new enumeration object:

>>>today=Weekdays.mon

The values can be compared:

>>>iftoday==Weekdays.fri:...print"Get ready for the weekend"

Values within an enumeration cannot be meaningfully compared exceptwith values from the same enumeration. The comparison operationfunctions returnNotImplemented[1] when avalue from an enumeration is compared against any value not from thesame enumeration or of a different type:

>>>gym_night=Weekdays.wed>>>gym_night.__cmp__(Weekdays.mon)1>>>gym_night.__cmp__(Weekdays.wed)0>>>gym_night.__cmp__(Weekdays.fri)-1>>>gym_night.__cmp__(23)NotImplemented>>>gym_night.__cmp__("wed")NotImplemented>>>gym_night.__cmp__(Grades.B)NotImplemented

This allows the operation to succeed, evaluating to a boolean value:

>>>gym_night=Weekdays.wed>>>gym_night<Weekdays.monFalse>>>gym_night<Weekdays.wedFalse>>>gym_night<Weekdays.friTrue>>>gym_night<23False>>>gym_night>23True>>>gym_night>"wed"True>>>gym_night>Grades.BTrue

Coercing a value from an enumeration to astr results in thestring that was specified for that value when constructing theenumeration:

>>>gym_night=Weekdays.wed>>>str(gym_night)'wed'

The sequence index of each value from an enumeration is exported as aninteger via that value’sindex attribute:

>>>gym_night=Weekdays.wed>>>gym_night.index3

An enumeration can be iterated, returning its values in the sequencethey were specified when the enumeration was created:

>>>print[str(day)fordayinWeekdays]['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']

Values from an enumeration are hashable, and can be used as dictkeys:

>>>plans={}>>>plans[Weekdays.sat]="Feed the horse"

The normal usage of enumerations is to provide a set of possiblevalues for a data type, which can then be used to map to otherinformation about the values:

>>>forreport_gradeinGrades:...report_students[report_grade]= \...[sforsinstudentsifstudents.grade==report_grade]

Rationale – Other designs considered

All in one class

Some implementations have the enumeration and its values all asattributes of a single object or class.

This PEP specifies a design where the enumeration is a container, andthe values are simple comparables. It was felt that attempting toplace all the properties of enumeration within a single classcomplicates the design without apparent benefit.

Metaclass for creating enumeration classes

The enumerations specified in this PEP are instances of anenumtype. Some alternative designs implement each enumeration as its ownclass, and a metaclass to define common properties of allenumerations.

One motivation for having a class (rather than an instance) for eachenumeration is to allow subclasses of enumerations, extending andaltering an existing enumeration. A class, though, implies thatinstances of that class will be created; it is difficult to imaginewhat it means to have separate instances of a “days of the week”class, where each instance contains all days. This usually leads tohaving each class follow the Singleton pattern, further complicatingthe design.

In contrast, this PEP specifies enumerations that are not expected tobe extended or modified. It is, of course, possible to create a newenumeration from the string values of an existing one, or evensubclass theenum type if desired.

Values related to other types

Some designs express a strong relationship to some other value, suchas a particular integer or string, for each enumerated value.

This results in using such values in contexts where the enumerationhas no meaning, and unnecessarily complicates the design. Theenumerated values specified in this PEP export the values used tocreate them, and can be compared for equality with any other value,but sequence comparison with values outside the enumeration isexplicitly not implemented.

Hiding attributes of enumerated values

A previous design had the enumerated values hiding as much as possibleabout their implementation, to the point of not exporting the stringkey and sequence index.

The design in this PEP acknowledges that programs will often find itconvenient to know the enumerated value’s enumeration type, sequenceindex, and string key specified for the value. These are exported bythe enumerated value as attributes.

Implementation

This design is based partly on a recipe[2] from thePython Cookbook.

The PyPI packageenum[3] provides a Pythonimplementation of the data types described in this PEP.

References and Footnotes

[1]
TheNotImplemented return value from comparison operationssignals the Python interpreter to attempt alternative comparisonsor other fallbacks.<http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy>
[2]
“First Class Enums in Python”, Zoran Isailovski,Python Cookbook recipe 413486<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486>
[3]
Python Package Index, packageenum<http://cheeseshop.python.org/pypi/enum/>

Copyright

This document has been placed in the public domain.


Source:https://github.com/python/peps/blob/main/peps/pep-0354.rst

Last modified:2025-02-01 08:59:27 GMT


[8]ページ先頭

©2009-2025 Movatter.jp