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

Nick Coghlan ncoghlan at gmail.com
Sun Apr 21 07:33:52 CEST 2013


On Sun, Apr 21, 2013 at 11:29 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> I would argue that it is the responsibility of enums to start with the least
> restrictions as is reasonable, and leave additional restrictions up to
> subclasses, rather than the other way around. (I'll just quietly mention the
> Liskov Substitution Principle here...) If some people need enums to have
> unique
> values, then enforcing that should be their responsibility, and not forced
> on
> all users whether they need that restriction or not.
>
> If there is enough demand for that, then perhaps the enum module could
> provide a
> standard mechanism for enforcing unique values, via a flag, or a subclass,
> say.

The PEP is fine, as it already allows duplicate names without encouraging them:

    class Insect(Enum):
        wasp = 1  # Preferred. Use this in new code.
        bee = 2
        ant = 3
    # Backwards compatibility aliases
    Insect.wsap = Insect.wasp

If you have a lot of such aliases:

   aliases = {
       "wasp": ["wsap"],
       ...
   }
   for attr, names in aliases.items():
       for name in names:
           setattr(Insect, name, getattr(Insect, attr))

A more concise syntax for handling duplicates may prove desirable at
some point in the future, but this is a case where encouraging
correctness by default is a good idea.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list