[Python-Dev] PEP 435 -- Adding an Enum type to the Python standard library

Barry Warsaw barry at python.org
Sat Apr 20 21:31:46 CEST 2013


On Apr 13, 2013, at 08:33 AM, Guido van Rossum wrote:

>(And yes, I am now +1 on documenting this mechanism.)

Here's what I've added to the flufl.enum documentation:

Customization protocol
======================

You can define your own enumeration value types by using the
``__value_factory__`` protocol.  This is how the ``IntEnum`` type is
defined.  As an example, let's say you want to define a new type of
enumeration where the values were subclasses of ``str``.  First, define your
enumeration value subclass.

    >>> from flufl.enum import EnumValue
    >>> class StrEnumValue(str, EnumValue):
    ...     def __new__(cls, enum, value, attr):
    ...         return super(StrEnumValue, cls).__new__(cls, value)

And then define your enumeration class.  You must set the class attribute
``__value_factory__`` to the class of the values you want to create.

    >>> class StrEnum(Enum):
    ...     __value_factory__ = StrEnumValue

Now, when you define your enumerations, the values will be ``str`` subclasses.
::

    >>> class Noises(StrEnum):
    ...     dog = 'bark'
    ...     cat = 'meow'
    ...     cow = 'moo'

    >>> isinstance(Noises.cow, str)
    True

-Barry


More information about the Python-Dev mailing list