Enum with only a single member

Ethan Furman ethan at stoneleaf.us
Tue Jan 10 00:01:25 EST 2017


On 01/09/2017 08:43 PM, Steven D'Aprano wrote:

> Is it silly to create an enumeration with only a single member? That is, a
> singleton enum?
>
> from enum import Enum
>
> class Unique(Enum):
>      FOO = auto()
>
>
> The reason I ask is that I have two functions that take an enum argument. The
> first takes one of three enums:
>
> class MarxBros(Enum):
>      GROUCHO = 1
>      CHICO = 2
>      HARPO = 3
>
> and the second takes *either* one of those three, or a fourth distinct value.
> So in my two functions, I have something like this:
>
>
> def spam(arg):
>      if isinstance(arg, MarxBros):
>          ...
>
>
> def ham(arg):
>      if isinstance(arg, MarxBros) or arg is Unique.FOO:
>          ...
>
>
> Good, bad or indifferent?

Well, the basic purpose of Enum is give meaningful names to otherwise magic constants, so while it certainly looks a bit unusual to have only one item in the enumeration, if that group naturally has only one item then sure, go for it!

--
~Ethan~



More information about the Python-list mailing list