[Python-Dev] [Python-checkins] peps: Pre-alpha draft for PEP 435 (enum). The name is not important at the moment, as (original) (raw)

MRAB python at mrabarnett.plus.com
Mon Feb 25 18:19:55 CET 2013


On 2013-02-25 16:37, Barry Warsaw wrote:

On Feb 25, 2013, at 07:12 AM, Ethan Furman wrote:

And if, in those places, the enums were based on ints (or strings), would it hurt you? Because in the places where I, as well as many others, use enums we need the int portion; and having to wrap the enum in an int() call is seven extra keystrokes (minor) and a heap of visual clutter (major), destroying any value the enum was supposed to have. Yes, I think enum values inheriting from int (or string) would hurt. First, as your question implies, which is it? int or str? Some people want int some want str. It can't be both, and I don't think we need two enum types. It's a deeper question though, because if enum values inherited from int, then people would expect things like Colors.red == 1 to work. Maybe you think that doesn't look so bad, but that also implies: >>> Colors = make('Colors', 'red green blue'.split()) >>> Animals = make('Animals', 'ant bee cat'.split()) >>> Colors.green == Animals.bee and that I have a problem with. While I generally recommend that that enum values be comparable by identity, not by equality, lots of people will still use == instead of is. My preference: def utter(animal): if animal is Animals.cat: print('meow') elif animal is Animals.bee: print('buzz') elif animal is Animals.ant: print('fphfft') but commonly used: def utter(animal): if animal == Animals.cat: print('meow') elif animal == Animals.bee: print('buzz') elif animal == Animals.ant: print('fphfft') Would we be doing either of those? Surely we would be using a dict instead, and what does a dict use, identity or equality?

In both cases, I want utter(Colors.green) and utter(2) to fail. In the latter, if enum values are derived from ints, the second example will succeed. Currently, in both cases utter(Animals.cat) succeeds.

Even worse, if my library defines an Animals enum and your library defines a different Animals enum, I do not want utter(YourAnimals.dog) to print "meow" :). I get that you think wrapping the value in int() is ugly. I have a compromise that you might find acceptable. EnumValues already have .enum and .name attributes, to give you the value's class and string name respectively. It would be trivial to add a .int attribute to return the value. Thus if you want the int value, it would be easy enough to say Colors.green.int or Animals.bee.int https://bugs.launchpad.net/flufl.enum/+bug/1132859



More information about the Python-Dev mailing list