how to check if a variable is of type enum in python

Prabhakar Shanmugam picture Prabhakar Shanmugam · Jul 15, 2016 · Viewed 21.3k times · Source

I have an enum like this

@enum.unique
class TransactionTypes(enum.IntEnum):
    authorisation = 1
    balance_adjustment = 2
    chargeback = 3
    auth_reversal = 4

Now i am assigning a variable with this enum like this

a = TransactionTypes

I want to check for the type of 'a' and do something if its an enum and something else, if its not an enum

I tried something like this

if type(a) == enum:
    print "do enum related stuff"
else:
    print "do something else"

The problem is it is not working fine.

Answer

Ethan Furman picture Ethan Furman · Jul 15, 2016

Now i am assigning a variable with this enum like this

a = TransactionTypes

I hope you aren't, because what you just assigned to a is the entire enumeration, not one of its members (such as TransactionTypes.chargeback) If that is really what you wanted to do, then the correct test would be:

if issubclass(a, enum.Enum)

However, if you actually meant something like:

a = TransactionTypes.authorisation

then the test you need is:

# for any Enum member
if isinstance(a, Enum):

or

# for a TransactionTypes Enum
if isinstance(a, TransactionTypes):