Python print class member name from value

Question:

I have a class with list of class members (variabls), each assigned to its own value.

class PacketType:
    HEARTBEAT      = 0xF0
    DEBUG          = 0xFC
    ECHO           = 0xFF

    @staticmethod
    def get_name(value):
        # Get variable name from value
        # Print the variable in string format
        return ???

If I call PacketType.get_name(0xF0), I’d like to get return as "HEARTBEAT".
Does python allow this, or is the only way to make list of if-elif for each possible value?

Asked By: tilz0R

||

Answers:

Why not use dictionary to store packet types?

class PacketType:
    packets = {
        0xF0: 'HEARTHBEAT',
        0XFC: 'DEBUG',
        0XFF: 'ECHO'
    }

    @classmethod
    def get_name(cls, value):
        return cls.packets[value]
Answered By: Aiq0

The below works. (But I dont understand why you want to have such thing)

class PacketType:
    HEARTBEAT = 0xF0
    DEBUG = 0xFC
    ECHO = 0xFF

    @staticmethod
    def get_name(value):
        for k, v in PacketType.__dict__.items():
            if v == value:
                return k
        return None


print(PacketType.get_name(0xFF))

output

ECHO
Answered By: balderman
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.