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.
Answers:
Use isinstance
:
isinstance(x, Enum)
x
has type EnumA
, none of the other things.
enum
is a module.
EnumType
isn’t defined at all is the metaclass used to define Enum
.
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
.
To know the type of the variable you should compare it with EnumA or EnumB, example :
type(x) is EnumA
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.
Use isinstance
:
isinstance(x, Enum)
x
has type EnumA
, none of the other things.
enum
is a module.EnumType
isn’t defined at allis the metaclass used to defineEnum
.Enum
is a class defined in theenum
module; it’s the parent class ofEnumA
.
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
.
To know the type of the variable you should compare it with EnumA or EnumB, example :
type(x) is EnumA