[Python-ideas] another enum implementation

Senthil Kumaran senthil at uthcode.com
Wed Feb 13 07:18:03 CET 2013


Two comments.

1. When it is fully generalized, is type is the way to to specify the
type of enums? Or there will be helper functions or classes that can
specify the type of enum one desires.
2. Personally, I have resorted to using namedtuples for enum like
behavior. How would this class benefit me? Any edification would be
helpful.

On Tue, Feb 12, 2013 at 9:04 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> 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~
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list