[Python-ideas] constant/enum type in stdlib

Tim Delaney timothy.c.delaney at gmail.com
Sun Feb 10 23:43:45 CET 2013


On 4 February 2013 11:17, Tim Delaney <timothy.c.delaney at gmail.com> wrote:

> On 4 February 2013 10:53, João Bernardo <jbvsmo at gmail.com> wrote:
>
>> Hi, about this enum/const thing, The use case I like more is a class
>> where you know all the
>> instances and not just a sequence of names.
>> Particularly It would be nice to have custom attributes and methods
>> besides the value and the name.
>>
>> I have my own implementation with a basic api somewhat borrowed from
>> flufl.enum (plus a lot of other stuff),
>> but with this kind of support: https://github.com/jbvsmo/makeobj
>>
>
> I considered it, and in fact you could almost do it with my implementation
> by using a custom subclass of EnumValue (except trying it has just exposed
> a design flaw with the whole _EnumProxy bit). Works if you create the enum
> in the same module as EnumValues, fails otherwise. Going to have to have a
> rethink.
>

Fixed the _EnumProxy issue (but it's a kludge - I've used sys._getframe() -
there's probably a better way). I've also made it so that you can override
the metaclass to return a subclass of EnumValue.

Now you can do something like:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from enum import Enum, EnumValue, EnumMeta
>>>
>>> class MyEnumValue1(EnumValue):
...     pass
...
>>> class MyEnumMeta1(EnumMeta):
...     @classmethod
...     def _create_value(cls, key, value):
...         return MyEnumValue1(key, value)
...
>>> class MyEnum1(Enum, metaclass=MyEnumMeta1):
...     VALUE1,
...     VALUE2
...
>>> class MyEnumValue2(EnumValue):
...     pass
...
>>> class MyEnumMeta2(MyEnumMeta1):
...     @classmethod
...     def _create_value(cls, key, value):
...         return MyEnumValue2(key, value)
...
>>> class MyEnum2(MyEnum1, metaclass=MyEnumMeta2):
...     VALUE3,
...     VALUE4
...
>>> print(repr(MyEnum1))
<enum '__main__.MyEnum1' {<MyEnumValue1 'MyEnum1.VALUE1': 0>, <MyEnumValue1
'MyEnum1.VALUE2': 1>}>
>>> print(repr(MyEnum2))
<enum '__main__.MyEnum2' {<MyEnumValue1 'MyEnum1.VALUE1': 0>, <MyEnumValue1
'MyEnum1.VALUE2': 1>, <MyEnumValue2 'MyEnum2.VALUE3': 2>, <MyEnumValue2
'MyEnum2.VALUE4': 3>}>
>>>

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


More information about the Python-ideas mailing list