[Python-ideas] constant/enum type in stdlib

Barry Warsaw barry at python.org
Thu Jan 31 21:46:30 CET 2013


On Jan 31, 2013, at 09:19 AM, Cameron Simpson wrote:

>  Color = enum(RED=None, WHITE=None, BLUE=None, yellow=9)

Oh, I forgot to mention that flufl.enum has an alternative API that's fairly
close to this, although it does not completely eliminate DRY[1]:

>>> from flufl.enum import make
>>> make('Animals', ('ant', 'bee', 'cat', 'dog'))
<Animals {ant: 1, bee: 2, cat: 3, dog: 4}>

You can also supply the elements as a 2-tuples if you want to specify the
values.  An example from the docs providing bit flags:

>>> def enumiter():
...     start = 1
...     while True:
...         yield start
...         start <<= 1
>>> make('Flags', zip(list('abcdefg'), enumiter()))
<Flags {a: 1, b: 2, c: 4, d: 8, e: 16, f: 32, g: 64}>

Cheers,
-Barry

[1] The first argument is currently necessary in order to give the right
printed representation of the enum.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130131/22835d7b/attachment.pgp>


More information about the Python-ideas mailing list