[Python-ideas] PEP for enum library type?

Barry Warsaw barry at python.org
Wed Feb 13 23:25:49 CET 2013


On Feb 14, 2013, at 06:28 AM, Tim Delaney wrote:

>1. Values don't get repeated.

This is easy, and flufl.enum guarantees this, even for subclasses:

    >>> class Colors(Enum):
    ...    red = 1
    ...    blue = 1
    ... 
    Traceback (most recent call last):
    ...
    TypeError: Multiple enum values: 1
    >>> class Colors(Enum):
    ...    red = 1
    ...    blue = 2
    ... 
    >>> class MoreColors(Colors):
    ...    green = 2
    ... 
    Traceback (most recent call last):
    ...
    TypeError: Multiple enum values: 2

>2. Values don't get skipped (unless explicitly skipped);

Is #2 is the reason why you have different subclasses for flag enums, since
the definition of "skipped" is different?

Many folks have said they don't care about the actual enum values, so for
them, skips don't matter.  Setting aside explicit skips, you can add such
verification with a class decorator, e.g.:

-----snip snip-----
from flufl.enum import Enum

def noskips(cls):
    for i, intval in enumerate(cls, start=1):
        if i != int(intval):
            raise TypeError('Skipped value: {}'.format(i))
    return cls

@noskips
class GoodColors(Enum):
    green = 3
    blue = 1
    red = 2

@noskips
class BadColors(Enum):
    green = 4
    blue = 1
    red = 2

$ python3 noskips.py
Traceback (most recent call last):
...
TypeError: Skipped value: 3
-----snip snip-----

>If you can convert from the string name to the enum, it makes the enum
>suitable as a transport mechanism.

    >>> from flufl.enum import make
    >>> Colors = make('Colors', 'red green blue'.split())
    >>> Colors['red']
    <EnumValue: Colors.red [int=1]>
    >>> Colors[2]
    <EnumValue: Colors.green [int=2]>
    >>> Colors[Colors.green.name]
    <EnumValue: Colors.green [int=2]>

Cheers,
-Barry
-------------- 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/20130213/d975fc9d/attachment.pgp>


More information about the Python-ideas mailing list