[Python-ideas] constant/enum type in stdlib

Tim Delaney timothy.c.delaney at gmail.com
Mon Feb 11 07:59:55 CET 2013


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

> I've also made it so that you can override the metaclass to return a
> subclass of EnumValue.
>

Expanded on this a bit to simplify things. Now to use a different type you
can just go:

 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
>>>
>>> class MyEnumValue1(EnumValue):
...     pass
...
>>> class MyEnum1(Enum, metaclass=Enum.subtype(MyEnumValue1)):
...     VALUE1,
...     VALUE2
...
>>> class MyEnumValue2(EnumValue):
...     pass
...
>>> class MyEnum2(MyEnum1, metaclass=MyEnum1.subtype(MyEnumValue2)):
...     VALUE3,
...     VALUE4
...
>>> print(repr(MyEnum1))
<enum __main__.MyEnum1 {<MyEnumValue1 'VALUE1': 0>, <MyEnumValue1 'VALUE2':
1>}>
>>> print(repr(MyEnum2))
<enum __main__.MyEnum2 {<MyEnumValue1 'VALUE1': 0>, <MyEnumValue1 'VALUE2':
1>, <MyEnumValue2 'VALUE3': 2>, <MyEnumValue2 'VALUE4': 3>}>

The parameter passed to subtype() can be any callable that takes 2
parameters (key, value) and returns an instance of EnumValue.
Unfortunately, I can't see any way to avoid specifying the base class twice
(once as the base class, once for the metaclass=).

Similarly, passing the 'value_type' parameter to Enum.make() creates an
appropriate metaclass from the base class:

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
>>> class MyEnumValue1(EnumValue):
...     pass
...
>>> MyEnum1 = Enum.make('MyEnum1', ('VALUE1', 'VALUE2'),
value_type=MyEnumValue1)
>>> print(repr(MyEnum1))
<enum __main__.MyEnum1 {<MyEnumValue1 'VALUE1': 0>, <MyEnumValue1 'VALUE2':
1>}>

Whilst the original "use a different metaclass to produce values of a
different type" was possibly feature-creep, these modifications at least
make it pretty painless to use.

Overall, I'm pretty happy with where this is now, except for the use of
sys._getframe().

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


More information about the Python-ideas mailing list