Representing enum style values w/ pretty printing?
Posted: Fri Mar 26, 2021 1:56 am
I've got a board that's sending "magic values" across the wire to my board running MicroPython. I've got these currently represented as constants in a class. I'd like to have a string conversion function that pretty prints the values but I'm having trouble figuring out how to do it.
Example:
I tried using a dict inside my class but didn't get it to work. I'm guessing my __str__ function has an issue.
If there's a more Pythonic to do it I'm not tied to the representation above. I've been doing C & C++ for a long time but I'm fairly new to Python so I'm probably missing something easy.
Example:
Code: Select all
class CommandCodes:
Death = const(0x0001)
Life = const(0x0002)
Universe = const(0x0040)
Everything = const(0x0042)
# something else here to make it prettily convert to a string...
value = CommandCodes::Everything
print( str(value)) # I'd like it to print "Everything"
Code: Select all
d = {Death:'Death', Life:'Life', Universe:'Universe', Everything:'Everything'}
def __str__(self)
return d[self]