[Python-Dev] PEP-435 reference implementation (original) (raw)
Steven D'Aprano steve at pearwood.info
Thu May 2 04:33:06 CEST 2013
- Previous message: [Python-Dev] PEP-435 reference implementation
- Next message: [Python-Dev] PEP-435 reference implementation
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 02/05/13 02:43, Guido van Rossum wrote:
Here's how I would implement "extending" an enum if subclassing were not allowed:
class Color(Enum): red = 1 white = 2 blue = 3 class ExtraColor(Enum): orange = 4 yellow = 5 green = 6 flagcolors = set(Color) | set(ExtraColor) Now I can test "c in flagcolors" to check whether c is a flag color.
Earlier you argued that testing for enums should be done with isinstance, not "in". Or did I misunderstood? So I would have thought that isinstance(c, (Color, ExtraColor)) would be the way to check c.
I would prefer to write "c in ExtraColor", assuming c extends Color.
Lookups by value also become more complex. Instead of c = ExtraColor[value], this leads to two choices, both of which are equally ugly in my opinion:
c = [c for c in flag_colors if c.value == value][0]
try: c = ExtraColor[value] except: # I'm not sure what exception you get here c = Color[value]
There is a further problem if the two enum classes have duplicate values, by accident or design. Accident being more likely, since now you have no warning when ExtraColor defines a value that duplicates something in Color. flag_colors will now contain both duplicates, since enum values from different enums never compare equal, but that's probably not what you want.
-- Steven
- Previous message: [Python-Dev] PEP-435 reference implementation
- Next message: [Python-Dev] PEP-435 reference implementation
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]