[Python-ideas] constant/enum type in stdlib

Tim Delaney timothy.c.delaney at gmail.com
Thu Jan 31 21:19:55 CET 2013


On 31 January 2013 12:27, Tim Delaney <timothy.c.delaney at gmail.com> wrote:

> On 31 January 2013 08:32, Terry Reedy <tjreedy at udel.edu> wrote:
>
>> On 1/30/2013 10:30 AM, Michael Foord wrote:
>>
>>> On 30 January 2013 15:22, Michael Foord
>>>
>>
>>      With a Python 3 metaclass that provides default values for *looked
>>>     up* entries you could have this:
>>>
>>>     class Color(Enum):
>>>          RED, WHITE, BLUE
>>>
>>>     The lookup would create the member - with the appropriate value.
>>>
>>> class values(dict):
>>>      def __init__(self):
>>>          self.value = 0
>>>      def __getitem__(self, key):
>>>
>>
>>
>> So RED, WHITE, BLUE are 1, 2, 3; not 0, 1, 2 as I and many readers might
>> expect. That aside (which can be fixed), this is very nice.
>>
>
> Here is a version that I think creates an enum with most of the features
> of traditional and modern enums.
>
> - Enum values are subclasses of int;
>
> - Only need to declare the enum key name;
>
> - Starts at zero by default;
>
> - Can change the start value;
>
> - Can have discontiguous values (e.g. 0, 1, 5, 6);
>
> - Can have other types of class attributes;
>
> - Ensures that there is a 1:1 mapping between key:value (throws an
> exception if either of these is violated;
>
> - Able to obtain the keys, values and items as per the mapping interface
> (sorted by value);
>
> - Lookup an enum by key or value;
>
> One thing to note is that *any* class attribute assigned a value which
> implements __index__ will be considered an enum value assignment.
>

Forgot about making it iterable - an easy-to-ad feature. Obviously it would
iterate over the EnumValue instancess.

Thought I'd better make it explicit as well that this was based on Michael
Foords brilliant work.

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130201/5b73c5d4/attachment.html>


More information about the Python-ideas mailing list