Should nested classes in an Enum be Enum members?
On 06/28/2018 01:11 AM, Steven D'Aprano wrote:
> On Wed, 27 Jun 2018 07:48:53 -0700, Ethan Furman wrote:
>> [Note: there is a similar thread on Python-Ideas, if you would like to
>> respond there.]
>> Consider the following Enum definition:
>> class Color(Enum):
>> RED = 1
>> GREEN = 2
>> BLUE = 3
>> def lower(self):
>> return self.name.lower()
>> def spam(self):
>> return "I like %s eggs and spam!" % self.lower
>> class SomeClass:
>> Which of the above Color attributes are enums, and which aren't?
> (In hindsight perhaps you should have called the class EnumType so that
> ambiguity would not exist. Then an enum would *always* refer to the
> members Color.RED etc, and never to Color itself.)
The problem then is the ambiguity between EnumMeta and EnumType. :/
>> - 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.).
>> Should `SomeClass` be an enum member? When would it be useful to
>> have an embedded class in an Enum be an enum member?
> I honestly cannot think of any reason to nest a class inside of an Enum
> class. But if I did, I would probably want it to be just a regular class,
> and not an enum member.
> If I wanted to nest an Enum class inside an Enum class (but why???) I'd
> just inherit from Enum:
> 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
[Colour.PrimaryColour <...>, Colour.SecondaryColour <...>]
or something else?
>> The only example I have seen so far of nested classes in an Enum is when
>> folks want to make an Enum of Enums, and the nested Enum should not
>> itself be an enum member. Since the counter-example already works I
>> haven't seen any requests for it. ;)
>> So I'm asking the community: What real-world examples can you offer for
>> either behavior? Cases where nested classes should be enum members, and
>> cases where nested classes should not be members.
> Is this a trick question?
Heh. Not at all. It is entirely possible to have a real use-case which we cannot model the way we want in code.