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

Guido van Rossum guido at python.org
Fri Apr 26 04:38:22 CEST 2013


On Thu, Apr 25, 2013 at 7:13 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> I'm the one who said I didn't see any obvious barriers to the merger,
> but I've realised there is one, and it's similar to one namedtuple
> struggles with: how to handle method definitions.
>
> With the current flufl.enum design, if you want to give instances of a
> particular enum additional behaviour, you can use a custom item type
> and add the methods there. Simple and relatively obvious.
>
> With a merged design, it becomes *really* hard to give the instances
> custom behaviour, because the metaclass will somehow have to
> differentiate between namespace entries that are intended to be
> callables, and those which are intended to be instances of the enum.
> This is not an easy problem to solve.

It's really sad that this technical problem exists (and I realize what
it is) -- because the obvious syntax (whose equivalent works in Java,
BTW) *seems* so natural:

class Color:

  red = 1
  white = 2
  blue = 3
  orange = 4

  def wave(self, n=1):
    for _ in range(n):
      print('Waving', self)

a = Color.red
a.wave()
Color.orange.wave(3)

> So, while I was initially in the "merge them" camp, I'm back to
> thinking the core architecture of flufl.enum is correct, but there may
> be some API adjustment to do, such as:
>
> 1. Lose the __getitem__ on the metaclass, and replace that with __call__
> 2. Ensure that isinstance(MyEnum.item, MyEnum) returns True (even
> though it isn't really)

If the above syntax won't work, that isinstance() outcome isn't really
important. :-(

Can't we do some kind of callable check? There may be some weird
decorators that won't work, but they aren't likely to be useful in
this context.

> 3. Inspired by namedtuple, move the current Enum constructor
> functionality to an Enum._make() API (implemented either as a class
> method in Enum or as an ordinary method on the metaclass)

--
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list