Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get value for enum by default when used in comparison

I have created a Enum class as shown:

class MsgType(Enum):
    # ADMINISTRATIVE MESSAGE
    HEARTBEAT = "0"
    LOGON = "A"
    LOGOUT = "5"
    REJECT_SESSION_LEVEL = "3"
    RESEND_REQUEST = "2"
    SEQUENCE_RESET = "4"
    SESSION_REJECT = "3"
    TEST_REQUEST = "1"

I want to use this class for comparison with a string that I get after reading a message. I am comparing the values as shown. The value in msg_type is a of type str.

def read_admin_msg(message):
    msg_type = read_header(message)
    if msg_type == ct.MsgType.HEARTBEAT:
        print(msg_type)
    elif msg_type == ct.MsgType.LOGON:
        print(msg_type)
    elif msg_type == ct.MsgType.LOGOUT:
        print(msg_type)
    elif msg_type == ct.MsgType.REJECT_SESSION_LEVEL:
        print(msg_type)
    elif msg_type == ct.MsgType.RESEND_REQUEST:
        print(msg_type)
    elif msg_type == ct.MsgType.SEQUENCE_RESET:
        print(msg_type)
    elif msg_type == ct.MsgType.SESSION_REJECT:
        print(msg_type)
    elif msg_type == ct.MsgType.TEST_REQUEST:
        print(msg_type)
    else:
        print("Not found")
        print(msg_type)

My expectation is that for msg_type = "A" the statement msg_type == ct.MsgType.LOGON should be True but instead else statement is executed.

If I write ct.MsgType.LOGON.value then I get the desired result. But I want this behavior to be default for the class. Which method should I override or should I try a different approach?

like image 570
ap14 Avatar asked Sep 14 '18 11:09

ap14


People also ask

How do I compare two enums in Python?

Use the value attribute on each enum member to compare enums in Python, e.g. Sizes. LARGE. value > Sizes. MEDIUM.

Can enums have default value?

The default value for an enum is zero. If an enum does not define an item with a value of zero, its default value will be zero.

Can enum variables be compared?

We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.


1 Answers

msg_type = "A" is the value of the Enum. You need to change one side of your equal comparisons. Either:

elif msg_type == MsgType.LOGON.value:
    print(msg_type)

or this:

# This one is probably preferred
elif MsgType(msg_type) == MsgType.LOGON:
    print(msg_type)

EDIT: I see your statement about using .value now. That's just how these enums work...if you want to override the __eq__ on your MsgType class, you can. But you'd be breaking the default equality comparison for Enums in the process, and you'd have to have special type checking in there for checking if your left/right side is a string/Enum/etc. I'd just make your read_header function return an instance of the Enum, and not the string value.

like image 199
wholevinski Avatar answered Nov 14 '22 21:11

wholevinski