[Python-Dev] PEP 435 - requesting pronouncement

Steven D'Aprano steve at pearwood.info
Sun May 5 19:43:09 CEST 2013


On 06/05/13 03:07, Charles-François Natali wrote:
> I'm chiming in late, but am I the only one who's really bothered by the syntax?
>
> class Color(Enum):
>      red = 1
>      green = 2
>      blue = 3
>
> I really don't see why one has to provide values, since an enum
> constant *is* the value.
> In many cases, there's no natural mapping between an enum constant and
> a value, e.g. there's no reason why Color.red should be mapped to 1
> and Color.blue to 3.


The functional API provides a way to conveniently create enums without caring what value they get. Other than that, the PEP explains that there was an early proposal to declare names without values:

# rejected syntax
class Color(Enum):
     red
     green
     blue


but this was rejected for being too magical, and too confusing to those who aren't expecting it.


> Furthermore, the PEP makes it to possible to do something like:
>
> class Color(Enum):
>      red = 1
>      green = 2
>      blue = 3
>      red_alias = 1
>
>
> which is IMO really confusing, since enum instances are supposed to be distinct.

Enums often have duplicate values, sometimes to provide aliases, sometimes to correct spelling errors, or to manage deprecated names, etc.

class Color(Enum):
     red = 1
     green = 2  # this is the preferred spelling
     blue = 3
     gren = green  # oops, do not remove, needed for backwards compatibility


E.g. I googled on "C enum" and the very first hit includes a duplicate value:

http://msdn.microsoft.com/en-AU/library/whbyts4t%28v=vs.80%29.aspx

And two examples from asm-generic/errno.h:

#define EWOULDBLOCK     EAGAIN  /* Operation would block */
#define EDEADLOCK       EDEADLK



> All the languages I can think of that support explicit values (Java
> being particular in the sense that it's really a full-fledge object
> which can have attributes, methods, etc) make it optional by default.
>
> Finally, I think 99% of users won't care about the assigned value
> (which is just an implementation detail), so explicit value will be
> just noise annoying users (well, me at least :-).


Compatibility with (e.g.) C enums is an important use-case for these, and in that case you likely will care about the actual value.


-- 
Steven


More information about the Python-Dev mailing list