Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python print class member name from value

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading