[Python-ideas] PEP for enum library type?

Brett Cannon brett at python.org
Wed Feb 13 17:26:26 CET 2013


On Tue, Feb 12, 2013 at 11:07 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

>
> On 13 Feb 2013 09:11, "Tim Delaney" <timothy.c.delaney at gmail.com> wrote:
> >
> > On 13 February 2013 09:56, Guido van Rossum <guido at python.org> wrote:
> >>
> >> Frankly, enums are not that useful in small programs. For large
> >> programs or libraries, and especially for public APIs, the extra cost
> >> of defining the enum shouldn't count against them.
> >>
> >> Let's just import Barry's enums into the stdlib.
> >
> >
> > That's entirely your call. FWIW I probably won't use them, as they fail
> to meet my needs for an enum, #1 being not having to specify their values
> in any way if I don't want to. Once you get past 3 or 4 values, it's too
> easy to miss or reuse a value.
>
> What's wrong with enum.make? That just accepts the sequence of names
> namedtuple style, no values specified anywhere.
>
>
> Georg called it ugly, but that's the only complaint I remember reading. I
too find them ugly but not enough to not say this isn't the best solution
considering everyone's complaints of verbosity (e.g. Guido not liking
excessive quoting), magic (e.g. all non-explicit proposals that don't
involve calling a classmethod like val()), and conciseness (e.g. not having
to specify every value).

Heck, if it was me I would just do::

  import types

  def make_enum(keys, *, value=None):
    """For incremental numbers: ``lambda key, index: index``.
    For bitwise flags: ``lambda key, index: 2**index``.

    Could change to take an iterator instead of a lambda and simply
special-case the `None` argument for strings,
    but that seems needlessly limiting when the integer case is probably
for interfacing with some C code.
    """
    if value is None:
      value = lambda key, index: key
    items = {}
    for key, index in enumerate(keys.split()):
      items[key] = value(key, index)
    return types.SimpleNamespace(**items)  # Creating a read-only subclass
is trivial

But I know people will want fancier reprs, globally unique objects, etc.
instead of just some simple way to create an object with attributes
referencing automatically-generated, unique, predictable values (which is
all I would want from an enum).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130213/abf4c72b/attachment.html>


More information about the Python-ideas mailing list