Enum with only a single member

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Jan 10 00:41:22 EST 2017


Steven D'Aprano writes:

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

With a class of its own, the single value can be identified by its class
uniformly with the other relevant values.

def ham(arg):
    if insinstance(arg, (MarxBros, Unique)):
        ...

Seems good to me.



More information about the Python-list mailing list