[Python-ideas] Enums

Giampaolo Rodolà g.rodola at gmail.com
Wed Jul 27 13:57:34 CEST 2011


2011/7/25 Barry Warsaw <barry at python.org>

> On Jul 24, 2011, at 05:33 PM, Guido van Rossum wrote:
>
> >For enums, I think we should just pick a solution. I'm in favor of
> >Barry Warsaw's version, flufl.enum.
>
> Thanks!  I would be quite happy to see the library pulled into the stdlib,
> and
> I'd be willing to maintain a backward compatible standalone version for
> older
> Pythons.
>
> For me, the API has been quite stable.  The last thing I added was Michael
> Foord's make_enum() contribution, and PJE's fix for pickling.  I haven't
> felt
> a burning need to add anything else really in quite some time.
>


 >>> from flufl.enum import Enum
 >>> class Colors(Enum):
 ...     red = 1
 ...     green = 2
 ...     blue = 3

What I find uncomfortable with this is the extra "Colors" name space.
Say we change all the socket module constants to make use of this, what will
we have?

>>> socket.AF_INET
<EnumValue: Constants.AF_INET [int=2]>

...and:

>>> socket.Constants.AF_INET
<EnumValue: Constants.AF_INET [int=2]>

...? Is that correct?

Also:

>>> socket.AF_INET
<EnumValue: Constants.AF_INET [int=2]>
>>> socket.AF_INET == 2
False
>>>

This shouldn't be underestimated: I've seen code comparing against plain
integers rather than constants more than once, and that code would
eventually break.
Personally I've never felt the need of any kind of "enum" type.
On the other hand I would welcome a "named constant" type of some kind but
IMO, it should remain a base integer and provide just a minimal extra layer
of usability, such as:

class constant(int):
    """A constant type; overrides base int to provide a useful name on
str()."""

    def __new__(cls, value, name, doc=None):
        inst = super(constant, cls).__new__(cls, value)
        inst._name = name
        if doc is not None:
            inst.__doc__ = doc
        return inst

    def __str__(self):
        return self._name

>>> STATUS_RUNNING = constant(0, "running")
>>> STATUS_RUNNING
0
>>> str(STATUS_RUNNING)
"running"
>>>


In summary, I'm -1 about including this into the stdlib and change all the
stdlib constants in accordarce.

My 2 cents.


--- Giampaolo
http://code.google.com/p/pyftpdlib/<http://code.google.com/p/psutil/downloads/list>
http://code.google.com/p/psutil/<http://code.google.com/p/psutil/downloads/list>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110727/ba0d57cc/attachment.html>


More information about the Python-ideas mailing list