[Python-ideas] PEP for enum library type?

Ethan Furman ethan at stoneleaf.us
Tue Feb 12 23:14:22 CET 2013


On 02/12/2013 12:38 PM, Yuval Greenfield wrote:
> On Tue, Feb 12, 2013 at 9:58 PM, Ethan Furman <ethan at stoneleaf.us
> <mailto:ethan at stoneleaf.us>> wrote:
>
>     1)  Magic is fun.  :)
>
>
> I heartily agree. Check this out:
>
>  >>> RED, GREEN, BLUE = enum()
>  >>> print(RED, GREEN, BLUE)
> 0 1 2
>  >>> LEFT, TOP, RIGHT, DOWN = enum()
>  >>> print(LEFT, TOP, RIGHT, DOWN)
> 0 1 2 3
>
>
> And here's the dirty trick....
>
> import inspect
> def enum():
>      """If you use this  your computer will most likely burst ablaze and
> your teeth will fall off"""
>      frame = inspect.stack()[1][0]
>      # 4 = 3 for the function call "enum()", 1 for the opcode
> "UNPACK_SEQUENCE",
>      # the next two bytes represent how many things we need to unpack.
>      a, b = frame.f_code.co_code[frame.f_lasti + 4:frame.f_lasti + 6]
>      enum_len = a + b * 256
>      return range(enum_len)

That is pretty cool.

Now all it needs is a nice repr(), and appropriate comparisons with only 
int and same enum group.

Is it cross-Python?

--
~Ethan~




More information about the Python-ideas mailing list