[Python-ideas] PEP for enum library type?
Joao S. O. Bueno
jsbueno at python.org.br
Tue Feb 12 19:05:44 CET 2013
On 12 February 2013 13:31, Antoine Pitrou <solipsis at pitrou.net> 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)
That is too much ' ' typing - I think it would be ok, to have
it like that, but a helper function that would work just like
the namedtuple call:
Color = Enum("Color", "RED GREEN BLUE", int)
The magic of
class Color(Enum):
RED, GREEN, BLUE
is tempting, but basically, what is required so that it does not break
class Color(Enum):
RED = other_module.value
(without making "other_module" a new enum value :-) ) if not worth it,
IMHO.
such magic is implemented in Tim's proof of concept.
A midle term could be to allow declarations like
class Color(IntEnum):
RED, BLUE, GREEN
but with no other logic or expressions in the class body -- all names
showing up are strictly part of the sequence, and them have a constructor call,
with keyword arguments for all the other cases.
>
> 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.
+1
One other important point, that is missed somewhere along Tim's implementation:
the repr and str of the enum values should be the value's name - no need
to the fancy representation. Actually, the fancy representation defeats most
of the purpose of having the constants/enums
They could have a property like Enum._qualified_name if one needs it.
>
> Regards
>
> Antoine.
>
>
More information about the Python-ideas
mailing list