I have the following part of code in C:
typedef enum {
CAN_NORMAL_MODE = 0x00,
CAN_SLEEP_MODE = 0x01,
CAN_INTERNAL_LOOPBACK_MODE = 0x02,
CAN_LISTEN_ONLY_MODE = 0x03,
CAN_CONFIGURATION_MODE = 0x04,
CAN_EXTERNAL_LOOPBACK_MODE = 0x05,
CAN_CLASSIC_MODE = 0x06,
CAN_RESTRICTED_MODE = 0x07,
CAN_INVALID_MODE = 0xFF
} CAN_OPERATION_MODE;
//more code here in the middle...
d = something
switch (d) {
case CAN_NORMAL_MODE:
mode = CAN_NORMAL_MODE;
break;
case CAN_SLEEP_MODE:
mode = CAN_SLEEP_MODE;
break;
// more cases here, not shown for readability
default:
mode = CAN_INVALID_MODE;
break;
}
Here d is a byte that I read from other sources. The switch statement is inside another function, and more code is there, but I don't think it is necessary to show as it does nothing to do with this part.
My problem is: I'm trying to translate this code to Python, for reasons, so that it is sintactically similar to the original C code (that is, I don't want the Python code to be radically different, so another person that has worked with the original C code can understand and use easily the Python code). I'm not sure how to implement the functionality in this code snippet in Python language without doing an endless stream of if-elif...else statements. I think there should an easier (pythonic) way to do it, but I'm not sure how to implement the typedef, enum and switch statements in Python. I have read some ways to implement the enum clause creating a class with the aliases and values as attributes, like this:
class myClass():
def __init__(self):
self.CAN_NORMAL_MODE = 0x00
self.CAN_SLEEP_MODE = 0x01
self.CAN_INTERNAL_LOOPBACK_MODE = 0x02
#etc
I have also come across a clever way of implementing a switch statement in Python, with a function like this (without any relation to my actual problem, just to show the structure of the implementation):
def switch(argument):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
print switcher.get(argument, "Invalid month")
But I can't come across a way of combining this two things in an easy and understandable way. Thank you and have a nice day!