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

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

Here are two ways to fix the error:

  1. Check if the object has a __dict__ attribute
  2. Using the dir() function

Flow diagram

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

Reproducing the error

Scenario 1: Using vars() with immutable built-in types

Visual representation of generating TypeError - vars() argument must have __dict__ attribute

x = 5

print(vars(x))

Output

TypeError: vars() argument must have __dict__ attribute

Scenario 2: Using vars() with objects that explicitly lack a __dict__

class MyClass:
  __slots__ = ['a', 'b']

  def __init__(self, a, b):
    self.a = a
    self.b = b


obj = MyClass(1, 2)
print(vars(obj))

Output

TypeError: vars() argument must have __dict__ attribute

How to fix it?

Solution 1: Check if the object has a __dict__attribute

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

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

Solution 2: Using the dir() function

Visual representation of dir() function

Another way to fix the error is to use vars() with an appropriate object. If your goal is simply to see the attributes associated with an integer, you can use dir() instead of vars(). It returns a list of valid attributes for the object.

Example 1

x = 5

print(dir(x))

Output

Output of the dir() function

Example 2

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

Output of fixing the error

Related posts

TypeError: can’t convert np.ndarray of type numpy.object_

TypeError: doc2bow expects an array of unicode tokens on input, not a single string

TypeError: ‘numpy.float64’ object cannot be interpreted as an integer

TypeError: ‘numpy.float64’ object is not callable

TypeError: ‘float’ object is not subscriptable

Leave a Comment

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