[Python-ideas] PEP for enum library type?
Ethan Furman
ethan at stoneleaf.us
Tue Feb 12 18:07:12 CET 2013
On 02/12/2013 07:31 AM, Antoine Pitrou wrote:
> Le Tue, 12 Feb 2013 07:21:04 -0800,
> Eli Bendersky <eliben at gmail.com> a écrit :
>>
>> from enum import Enum
>>
>> class Color(Enum):
>> RED, BLUE, GREEN
>
> I think I'd favour a namedtuple-style approach, e.g.:
>
> class Color(Enum):
> fields = ('RED', 'BLUE', 'GREEN')
>
> (which allows you to build enums programmatically too)
>
> Also, I think you have to provide several classes, at least
> SequenceEnum and StringEnum, and perhaps also BitmaskEnum.
> It makes sense for them to be separate types, 1) because it makes it
> explicit how the given enum behaves, 2) because combining integer and
> str constants in an enum would be crazy.
I partially agree with Antoine; there should be three types of Enum
available:
- sequence (most common: 0, 1, 2, 3, etc.)
- flag (1, 2, 4, 8, etc.)
- unique ('on', 'off'; 'north', 'south', 'east', 'west')
and they shouldn't be mixed together higgledy-piggledy in the same class.
However, I like the simplicity of Tim's approach.
The result of the implementation I've been playing with looks something
like:
class Color(Enum):
type = 'sequence'
RED, GREEN, BLUE
class Geometry(Enum):
type = 'unique'
LEFT, RIGHT, TOP, BOTTOM
WEST, EAST, NORTH, SOUTH
class FieldType(Enum):
type = 'flag'
BINARY, AUTOINC, NULLABLE
The metaclass takes care of assigning the next value and selecting the
proper subclass; 'unique' values are lower-cased (LEFT -> 'left');
subclassing is possible; and each Enum value is properly an instance of
it's Enum class.
One important reason for having the different types of Enum is for
prototyping.
--
~Ethan~
More information about the Python-ideas
mailing list