Question

I am working on a method to return all the class variables as keys and values as values of a dictionary , for instance i have:

first.py

class A:
    a = 3
    b = 5
    c = 6

Then in the second.py i should be able to call maybe a method or something that will return a dictionary like this

import first

dict = first.return_class_variables()
dict

then dict will be something like this:

{'a' : 3, 'b' : 5, 'c' : 6}

This is just a scenario to explain the idea, of course i don't expect it to be that easy, but i will love if there are ideas on how to handle this problem just like dict can be used to set a class variables values by passing to it a dictionary with the variable, value combination as key, value.

Was it helpful?

Solution

You need to filter out functions and built-in class attributes.

>>> class A:
...     a = 3
...     b = 5
...     c = 6
... 
>>> {key:value for key, value in A.__dict__.items() if not key.startswith('__') and not callable(key)}
{'a': 3, 'c': 6, 'b': 5}

OTHER TIPS

Something like this?

  class A(object):
      def __init__(self):
          self.a = 3
          self.b = 5
          self.c = 6

  def return_class_variables(A):
      return(A.__dict__)


  if __name__ == "__main__":
      a = A()
      print(return_class_variables(a))

which gives

{'a': 3, 'c': 6, 'b': 5}

Use a dict comprehension on A.__dict__ and filter out keys that start and end with __:

>>> class A:
        a = 3
        b = 5
        c = 6
...     
>>> {k:v for k, v in A.__dict__.items() if not (k.startswith('__')
                                                             and k.endswith('__'))}
{'a': 3, 'c': 6, 'b': 5}

Best solution and most pythonic is to use var(class_object) or var(self) (if trying to use inside class).

This although do avoids dictionary pairs where the key is another object and not a default python type.

>>> class TheClass():
>>>    def __init__(self):
>>>        self.a = 2
>>>        self.b = 1
>>>        print(vars(self))
>>> class_object= TheClass()
{'a'=2, 'b'=1}

Or outside class

>>> vars(class_object)
{'a': 2, 'b': 1}

You can use __dict__ to get the list of a class variables. For example, if you have a class like this:

class SomeClass:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    def to_dict(self) -> dict:
        return {key: value for key, value in self.__dict__.items()}

You can get the list of variables this way:

some_class = SomeClass(1,2,3)
some_class.to_dict()

And the output will be:

{'a':1, 'b':2, 'c':3}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top