[Python-ideas] Enums

Antoine Pitrou solipsis at pitrou.net
Fri Jul 29 23:41:41 CEST 2011


On Sat, 30 Jul 2011 01:26:01 +1000
Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Sat, Jul 30, 2011 at 1:09 AM, Guido van Rossum <guido at python.org> wrote:
> > That's assuming the data export format doesn't support enums.
> >
> > I would fine enums whose str() is just an int pretty annoying. Note
> > that str(True) == repr(True) == 'True' and that's how I'd like it to
> > be for enums in general. If you want the int value, use int(e). If you
> > want the class name, use e.__class__.__name__ (maybe e.__class__ is
> > what you're after anyway). My observation is that most enums have
> > sufficiently unique names that during a debugging session the class is
> > not a big mystery; it's the mapping from value to name that's hard to
> > memorize. As a compromise, I could live with str(e) == 'red' and
> > repr(e) == 'Color.red'. But I don't think I could stomach str(e) == 1.
> 
> For enums that define new values which are not equivalent to the
> underlying values, I agree with you, but my concept for named values
> is to allow them to be almost entirely a drop-in replacement for the
> values they replace. For that more general use case, changing the
> result of str() would be problematic, since str() is often used to
> create command line APIs and other things.

I agree with that. repr() can be used to give further information (and
repr() or even ascii() should always be used when debugging anyway, not
str()).

Realistically, many potential uses of enums are tied to some underlying
C library - be it errnos, flags for os.open(), socket families, etc. It
would probably be wrong for an enum implementation not to support
these use cases.

Regards

Antoine.





More information about the Python-ideas mailing list