Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 942
Prabhakar Shanmugam Avatar asked Jul 15 '16 10:07

Prabhakar Shanmugam


People also ask

What is the type of enum in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.

How do I check if a string is enum?

Then you can just do: values. contains("your string") which returns true or false.


1 Answers

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):
like image 66
Ethan Furman Avatar answered Oct 06 '22 04:10

Ethan Furman