[Python-ideas] constant/enum type in stdlib

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Jan 30 05:58:37 CET 2013


Guido van Rossum wrote:

> class color(enum):
>   RED = value()
>   WHITE = value()
>   BLUE = value()

We could do somewhat better than that:

    class Color(Enum):
       RED, WHITE, BLUE = range(3)

However, it's still slightly annoying that you have to
specify how many values there are in the range() call.
It would be even nicer it we could just use an infinite
iterator, such as

    class Color(Enum):
       RED, WHITE, BLUE = values()

However, the problem here is that the unpacking bytecode
anally insists on the iterator providing *exactly* the
right number of items, and there is no way for values()
to know when to stop producing items.

So, suppose we use a slightly extended version of the
iterator protocol for unpacking purposes. If the object
being unpacked has an __endunpack__ method, we call it
after unpacking the last value, and it is responsible
for doing appopriate checking and raising an exception
if necessary. Otherwise we do as we do now.

The values() object can then have an __endunpack__
method that does nothing, allowing you to unpack any
number of items from it.

-- 
Greg



More information about the Python-ideas mailing list