How to Fix TypeError: vars() argument must have __dict__ attribute

The TypeError: vars() argument must have __dict__ attribute error occurs when you try to “call the built-in vars() function on an object that doesn’t have a __dict__ attribute”.

The vars() function is used to get an object’s __dict__ attribute, which contains its attributes in the form of a dictionary.

To fix this error, check if the object has a __dict__ attribute before calling vars() or using the dir() function.

Method 1: Check if the object has a __dict__attribute

Check if the object has a __dict__ attribute before calling the vars() function.

Example

class MyClass:
  pass


class MyClassWithoutDict:
  __slots__ = []


obj1 = MyClass()
obj2 = MyClassWithoutDict()

if hasattr(obj1, '__dict__'):
  print(vars(obj1))
else:
  print("obj1 doesn't have a __dict__ attribute")

if hasattr(obj2, '__dict__'):
  print(vars(obj2))
else:
  print("obj2 doesn't have a __dict__ attribute")

Output

{}
obj2 doesn't have a __dict__ attribute

Method 2: Using the dir() function

Use the dir() function to get all object attributes, including its class attribute.

class MyClass:
  pass


class MyClassWithoutDict:
  __slots__ = []


obj1 = MyClass()
obj2 = MyClassWithoutDict()

print("Attributes of obj1:")
for attribute in dir(obj1):
  print(f"{attribute}: {getattr(obj1, attribute)}")

print("\nAttributes of obj2:")
for attribute in dir(obj2):
  print(f"{attribute}: {getattr(obj2, attribute)}")

Output

vars() argument must have __dict__ attribute

In this code, we used the dir() function to get all object attributes, including its class attributes.

Remember that dir() will not give you the same output as vars(), as it lists all attributes, not just the instance attributes stored in the object’s __dict__.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.