OSDir


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Should nested classes in an Enum be Enum members?


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
>        @property
>        def lower(self):
>            return self.name.lower()
>        def spam(self):
>            return "I like %s eggs and spam!" % self.lower
>        class SomeClass:
>            pass
> 
> Which of the above Color attributes are enums, and which aren't?

The question is ambiguous in the case of SomeClass. It could mean that:

- SomeClass is the same kind of thing as Color (an Enum subclass);

- SomeClass is the same kind of thing as Color.RED (an enum member);

- or neither of the above.


(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.)

Without trying it, or reading ahead, I would not want to guess which was 
the case.

[

s
p
o
i
l
e
r
 
s
p
a
c
e

]

> 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?


> Question:
> 
>    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


> 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?

:-)





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