Python compare type of (str, enum) classes

Question:

I have multiple enums defined with

from enum import Enum

class EnumA(str, Enum):
    RED = "red"

class EnumB(str, Enum):
    BLUE = "blue"

How do I compare the type of these classes/enums with say x=EnumA.RED? The following doesn’t work.

type(x) is enum
type(x) is EnumType
type(x) is Enum

I don’t want to compare the classes directly, since I have a lot of enums.

Asked By: TheRuedi

||

Answers:

Use isinstance:

isinstance(x, Enum)
Answered By: Unmitigated

x has type EnumA, none of the other things.

  1. enum is a module.
  2. EnumType isn’t defined at all is the metaclass used to define Enum.
  3. Enum is a class defined in the enum module; it’s the parent class of EnumA.

In any case, never compare type objects directly. Use isinstance to determine if a value is of a given type. (For checking the type of an object, you virtually never care about the difference between a class and its superclass(es).)

>>> isinstance(x, EnumA)
True
>>> isinstance(x, Enum)
True

The latter is true because EnumA is a subclass of Enum.

Answered By: chepner

To know the type of the variable you should compare it with EnumA or EnumB, example :

type(x) is EnumA

Answered By: Stg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.