[Python-ideas] another enum implementation

Ethan Furman ethan at stoneleaf.us
Wed Feb 13 06:04:39 CET 2013


I realize this isn't going very far, but I would still appreciate 
feedback.  :)

The code is here:
https://bitbucket.org/stoneleaf/enum

It is based on ideas from Michael Foord, Antoine Pitrou, and 
(eventually) Ted Delaney.


Enum only accepts upper-case names as enum candidates; all enum values 
must be the same: either 'sequence' (0, 1, 2, etc) or 'flag' (1, 2, 4, 
etc.) or 'unique' (north, south, east, west, etc.); and extending via 
subclassing is possible.

Sample code:

class Color(Enum):
     type = 'sequence'
     BLACK
     RED
     GREEN = 4
     BLUE
print Color
# Color(BLACK:0, RED:1, GREEN:4, BLUE:5)

class MoreColor(Color):
     MAGENTA
     YELLOW
     CYAN
print MoreColor
# MoreColor(BLACK:0, RED:1, GREEN:4, BLUE:5, MAGENTA:6, YELLOW:7,
#	    CYAN:8)


class DbfType(Enum):
     type = 'unique'
     CLP
     DB3
     VFP
--> print(enum.DbfType)
# DbfType(DB3:'db3', CLP:'clp', VFP:'vfp')

class SomeFlags(Enum):
     type = 'flag'
     ON_DISK
     HAS_MEMO
     LARGE_CHAR
     UNICODE
--> print(enum.SomeFlags)
# SomeFlags(ON_DISK:1, HAS_MEMO:2, LARGE_CHAR:4, UNICODE:8)

class Error(Enum):
     type = 'sequence'
     THIS
     THAT
     The_Other		# raises NameError
     THOSE = 1		# raises InvalidEnum

-->enum.Color.RED
Color('RED')

-->enum.Color.RED == 1
True

-->int(enum.Color.RED)
1

-->enum.SomeFlags.ON_DISK
SomeFlags('ON_DISK')

-->enum.SomeFlags.ON_DISK == 1
True

-->int(enum.SomeFlags.ON_DISK)
1

-->enum.SomeFlags.ON_DISK == enum.Color.RED
False

-->enum.MoreColor.RED == 1
True

-->enum.MoreColor.RED == enum.Color.RED
True

-->enum.Color(1)
Color('RED')

-->enum.Color('RED')
Color('RED')

--> for color in enum.Color:
...   print(color)
...
BLACK
RED
GREEN
BLUE

--> for color in enum.Color:
...   print(repr(color))
...
Color('BLACK')
Color('RED')
Color('GREEN')
Color('BLUE')


I would appreciate any comments on both the API, and the code behind it.

Thanks.

--
~Ethan~



More information about the Python-ideas mailing list