[Python-Dev] enum discussion: can someone please summarize open issues?

Ethan Furman ethan at stoneleaf.us
Mon Apr 29 06:02:15 CEST 2013


[re-directing back to python-dev]

On 04/28/2013 08:42 PM, Davis Silverman wrote:
> as a not super experienced python developer, when i see Season('AUTUMN') it looks like im creating an a Season object. I
> understand your resoning, that it acts like a boolean singleton, however, i feel it would confuse many, and isn't worth
> it. From what i see, its meant to be a lookup sort of thing, but it doesnt really feel like one.
>
> Or am i completely wrong about something?

As far as you are concerned, you are creating a Season object.  That it happens to be a pre-existing Season object is an 
implementation detail, and the whole thing would work just as well if it did indeed create a brand new object (you 
couldn't use `is` then, but in general `is` shouldn't be used anyway and I see no reason why `is` should be encouraged 
with Enums; use `==`).

Two examples:

   - the first few integers (up to 256 now, I think) are pre-created by the interpreter; when you do `int('7')` you are 
not getting a brand-new, never before used, integer 7 object, you're getting a cached integer 7 object.

   - all booleans (yup, both of them ;) are pre-created; when you ask for a True or a False, you are not getting a brand 
new one.

Since `is` is discouraged, both of those cases could go the other way (always creating a brand new object) and properly 
written programs would continue to run just fine -- slower, but fine.

Enums are the same: they could return brand new instances every time, and programs using `==` to compare will keep on 
working.  That they don't is an implementation detail.

The real guarantee with enums is that once you have one created you'll only ever see the original values; so

   class Last(Enum):
       X = 1
       Y = 2
       Z = 3

will only have three possible elements, X, Y, and Z, and X will always have the value of 1, Y will always have the vale 
of 2, and Z will always have the value of 3.  If you try and get `Last("W")` you'll trigger an exception, just like you 
do with `int("house")`.

--
~Ethan~


More information about the Python-Dev mailing list