Search code examples
pythonooppython-class

How to return class variable as a dict?


I am trying to write a method in my class and trying to return as dict.

class Test(object):
    location = 'Dhaka'

    @classmethod
    def get_items(cls):
        items = dict()

        for item in cls:
            items[item.name] = item.value

        return items


class NewTest(Test):
    lat = 4444

and I am trying to get the result following this:

print(NewTest.get_items())
{'location': 'Dhaka', 'lat': 4444}

But returning error like that type can't be iterated.


Solution

  • You can look through the contents of applying dir() to the class to get all its attributes, but need some way to filter out things with special names while looking for class variables. A fairly fast way to do that would be with regular expression pattern matching to recognize them. You'll also need filter out callable values like the get_items() classmethod.

    Doing both is illustrated below.

    import re
    
    DUNDER = re.compile(r'^__[^\d\W]\w*__\Z', re.UNICODE)  # Special method names.
    
    
    class Test(object):
        location = 'Dhaka'
    
        @classmethod
        def get_items(cls):
            is_special = DUNDER.match  # Local var to speed access.
            items = {}
    
            for name in dir(cls):
                if not is_special(name):
                    value = getattr(cls, name)
                    if not callable(value):
                        items[name] = value
    
            return items
    
    
    class NewTest(Test):
        lat = 4444
    
    
    print(NewTest.get_items())  # -> {'lat': 4444, 'location': 'Dhaka'}