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?
Use the value attribute on each enum member to compare enums in Python, e.g. Sizes. LARGE. value > Sizes. MEDIUM.
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.
We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With