Get all class variables in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Get all class variables in Python #

To get all class variables:

  1. Use the dir() function to get a list of the names of the class's attributes.
  2. Filter out the attributes that start with a double underscore and the methods.
  3. The remaining attributes are all of the class's variables.
main.py
class Employee(): # 👇️ class variables cls_id = 'employee' another = 'foo' def __init__(self, id, name, salary): # 👇️ instance variables self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # ✅ get all class variables class_variables = [attribute for attribute in dir(Employee) if not attribute.startswith('__') and not callable(getattr(Employee, attribute)) ] print(class_variables) # 👉️ ['another', 'cls_id'] # ----------------------------------------------------- # ✅ get all instance variables result = list(bob.__dict__.keys()) print(result) # 👉️ ['id', 'name', 'salary'] print(bob.__dict__) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100}

The dir function returns a list of the names of the class's attributes, and recursively of the attribute of its base classes.

main.py
class Employee(): cls_id = 'employee' another = 'foo' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'another', 'cls_id'] print(dir(Employee)) class_variables = [attribute for attribute in dir(Employee) if not attribute.startswith('__') and not callable(getattr(Employee, attribute)) ] print(class_variables) # 👉️ ['another', 'cls_id']

We now have to filter out all attributes that start with two underscores and all methods.

The remaining items are the names of the class variables.

You can use a dict comprehension if you need to get a dictionary of the class variables and the corresponding values.

main.py
class Employee(): cls_id = 'employee' another = 'foo' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary result = {key: value for key, value in Employee.__dict__.items( ) if not key.startswith('__') and not callable(key)} print(result) # 👉️ {'cls_id': 'employee', 'another': 'foo'}

The __dict__ attribute returns a dictionary containing the object's properties and values.

We had to filter out keys that start with two underscores and methods just like in the previous example.

If you need to get all instance variables, use the __dict__ attribute.
main.py
class Employee(): cls_id = 'employee' another = 'foo' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) result = list(bob.__dict__.keys()) print(result) # 👉️ ['id', 'name', 'salary'] print(bob.__dict__) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100}

You can use the dict.keys() method to get only the keys of the dictionary.

The dict.keys method returns a new view of the dictionary's keys.

The last step is to use the list() class to convert the view to a list.

You can also use the vars() function in a similar way.

main.py
class Employee(): cls_id = 'employee' another = 'foo' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) result = list(vars(bob).keys()) print(result) # 👉️ ['id', 'name', 'salary'] # 👇️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(vars(bob))

The vars function takes an object and returns the __dict__ attribute of the given module, class, instance or any other object that has a __dict__ attribute.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.