[Python-ideas] Enums

Nick Coghlan ncoghlan at gmail.com
Fri Jul 29 07:29:03 CEST 2011


On Fri, Jul 29, 2011 at 3:00 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Guido van Rossum <guido at python.org> writes:
>
>> These could be two separate features. Named values could be a building
>> block for a built-in Enum type -- the named value would take care of
>> the str() and repr(), while the Enum type would only have to take care
>> of the nice syntax ("class Color(Enum): red = 1; ...") and just create
>> a bunch of named values in the class scope.
>
> +1.
>
> As for EnumValue instances having a defined order, thanks to my reading
> of <URL:http://en.wikipedia.org/wiki/Enumerated_type> I can now say that
> some of us want an enumerated type that is not ordinal, and others want
> an ordinal type.
>
> And non-ordinal enumerated types, built-in, could then further be used
> as the basis for a custom ordinal type.
>
> Hence:
>
> * a built-in “named value” feature
>
> * a built-in, or standard-library, non-ordinal enumerated type feature
>  (using the “named value” feature)
>
> * a standard-library ordinal type feature
>  (using the enumerated type feature)
>
> Would that make us all happy?

I like the tower, but I'd like to see us approach this incrementally.

1. Design and provide a standard "named value" feature

(CPython unfortunately makes it difficult to do this efficiently - we
need to add state to hold the name, but doing that in a way that is
compatible with the C layout of tuples and similar objects means the
state has to be stored in __dict__)

2. Perhaps provide a non-ordinal NamedGroup feature (avoiding the Enum
naming with its 'enumerated' ordinal implications)

Explicitly naming several values is likely to be clumsy enough that a
metaclass based solution may be a beneficial convenience API, but
Named Groups wouldn't enforce any additional behaviour on their
members. I'm not completely persuaded on this point as yet, but I can
see the merit of the argument.

As an initial step, I thinks that's the absolute limit of how far we
should go. I see it as similar to the handling of function annotations
- we can provide a standard infrastructure for naming instances
without otherwise affecting their behaviour, and then allow third
parties to build on that and see where they take it.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list