Python vars() Function – View Object’s Attributes

Python vars() Function

The vars() function returns the __dict__ attribute of an object. This is usually a dictionary containing all the writable attributes of the object. It’s useful when you want to inspect or work with an object's internal namespace.

Syntax

vars([object])

Parameters:

  • object (optional) – The object whose __dict__ attribute you want to access. If no argument is provided, it returns the dictionary of the local symbol table.

Returns:

  • A dictionary representing the __dict__ attribute of the object or the current local symbol table if no argument is given.

Example 1: Using vars() on a Class Instance

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

s = Student("Alice", "A")
print(vars(s))
{'name': 'Alice', 'grade': 'A'}

Why? Because vars(s) returns the dictionary of attributes of the s object.

Example 2: Using vars() Without Arguments

x = 10
y = "Hello"
print(vars())
{'x': 10, 'y': 'Hello', ...}

This shows the local symbol table as a dictionary. It's useful for debugging or introspection.

Use Case: When to Use vars()?

  • To inspect the attributes of an object (e.g., class instances)
  • For debugging and exploring local/global scope contents
  • When dynamically working with attributes and values

What if the Object Doesn’t Have __dict__?

If you pass an object that doesn’t have a __dict__ attribute, Python raises a TypeError.

print(vars(42))
TypeError: vars() argument must have __dict__ attribute

Interview Tip

Understanding vars() helps when you're dealing with object serialization, debugging tools, or custom class inspection.

Summary

  • vars() shows the __dict__ of an object (if present).
  • Without arguments, it shows the local symbol table.
  • Useful for introspection, debugging, and meta-programming.

Practice Problem

Create a class Book with attributes title and author. Create an object and print all its attributes using vars().

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

b = Book("Python 101", "John Doe")
print(vars(b))
Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗