30

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.

4
  • It's not clear what you're asking, what do you mean by 'class variables'?
    – Bi Rico
    Jan 24, 2014 at 0:50
  • Class attributes, the answers below was what i was looking for.:)
    – Plaix
    Jan 24, 2014 at 0:51
  • 1
    k, just keep in mind that will also include methods of the class and will not give you any attributes defined in a parent class.
    – Bi Rico
    Jan 24, 2014 at 0:54
  • Yes, the class i am working on contains only attributes no methods, thank you i will keep that in mind
    – Plaix
    Jan 24, 2014 at 0:56

7 Answers 7

45

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}
1
  • 6
    Minor correction: I think that should be ...and not callable(value)}.
    – realgeek
    Dec 21, 2016 at 21:43
3

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}
2
  • I would recommend renaming the class...for added clarity with respect to the return_class_variables() method. Feb 4, 2016 at 13:25
  • 1
    You're setting and returning instance variables, not the class variable. Class variables are not defined in __init__() but just after the class statement. Class variables are common to all instances, whereas instance variables belong to the instance only (the Class object can't access instance variables, although the opposite is possible).
    – Eric
    Nov 11, 2018 at 0:46
3

afkfurions highly upvoted and accepted answer is incomplete and contains a mistake that will be visible for less trivial classes. It will include things like classmethods and staticmethods in the result which is probably unwanted. Here is a version that will work (also including the fix suggested by realgeek):


class B:
    a = 3
    b = 2
    
    @classmethod
    def fn(cls):
        pass

    @staticmethod
    def foo():
        pass

    def method(self):
        pass

d = {
    key:value for key, value in B.__dict__.items() 
    if not key.startswith('__') 
    and not callable(value) 
    and not callable(getattr(value, "__get__", None)) # <- important
}
print(d) # {'a': 3, 'b': 2}

Explanation: A class-attribute may be a get-set-descriptor. In this case, accessing the value in the classes __dict__ will yield the object implementing the descriptor-protocol and not the value represented by that object.

1

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}
0
1

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}
0

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}
0

I would recommend using the built-in vars method of python. https://www.geeksforgeeks.org/vars-function-python/#

From the website:

vars(object)

The method returns the dict attribute for a module, class, instance, or any other object if the same has a dict attribute. If the object fails to match the attribute, it raises a TypeError exception. Objects such as modules and instances have an updatable dict attribute however, other objects may have written restrictions on their dict attributes. vars() acts like locals() method when an empty argument is passed which implies that the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

From your example:

  • Create an object instance (that has initialised values for each of the properties
a_obj = A()
  • Use the vars function
vars(a_obj)

Output:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.