Should nested classes in an Enum be Enum members?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jun 28 21:00:15 EDT 2018


On Thu, 28 Jun 2018 08:36:47 -0700, Ethan Furman wrote:

>>> Answer:
>>>
>>>     - RED, GREEN, and BLUE are members
>>>     - lower and spam() are not
>>>     - SomeClass /is/ a member (but not its instances)
>>
>> Is that by accident or by design?
> 
> By design.  It is entirely possible to want an enum of types (int,
> float, str, etc.).

Seems strange to me. Why enum of types but not an enum of functions or 
methods?

Perhaps you could have had an explicit decorator?


class Colours(Enum):
    RED = 1

    class Spam(object):
        pass

    @Enum.member
    class Eggs(object):
        pass


Colours.Eggs will be an enum member, Spam will not be.

But I suppose backwards compatibility rules that out.



>> class Colour(Enum):
>>      class PrimaryColour(Enum):
>>          RED = 1
>>          GREEN = 2
>>          BLUE = 3
>>          OCTARINE = 8
>>      class SecondaryColour(Enum):
>>          PUCE = 101
>>          MAUVE = 102
>>          BEIGE = 103
>>          TEAL = 104
> 
> This really seems to be the sticking point -- what should an Enum of
> Enums look like?  For example, should the above do
> 
>    --> list(Colour)
>    [Colour.PrimaryColour <...>, Colour.SecondaryColour <...>]
> 
> or something else?

I would expect the inner classes to disappear:

[Colour.RED, Colour.GREEN, ... Colour.PUCE, ... ]

unless I explicitly inspect their types:

type(Colour.RED)
=> returns Colour.PrimaryColour


But maybe there's another way to get that same effect?

# ???
class PrimaryColour(Enum):
    RED = 1
    ...
class SecondaryColour(Enum):
    ...

Colour = PrimaryColour + SecondaryColour




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list