Fundamentals 2 min read

Unlock Python’s vars(): Retrieve Object Attributes and Values Easily

This article explains Python’s built‑in vars() function, detailing its syntax, parameters, return value, and how it mirrors locals() when called without arguments, and provides clear examples showing its use with modules, classes, instances, and objects that define __dict__.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Unlock Python’s vars(): Retrieve Object Attributes and Values Easily

Overview

The vars() built‑in returns a dictionary containing an object’s attribute names and their corresponding values. When called without an argument it behaves like locals(), exposing the current local symbol table.

Syntax

vars([object])

Parameters

object – Any Python object (module, class, class instance, or any object that defines a __dict__ attribute).

Return Value

A dict mapping attribute names to their values. If no argument is supplied, the dictionary represents the current scope’s local variables.

Usage Examples

1. No argument – same as locals()

Inside a function, calling vars() returns all local variables:

def demo():
    a = 10
    b = 'text'
    print(vars())
# Output: {'a': 10, 'b': 'text'}

2. With an argument – inspect any object

You can pass a module, class, instance, or any object that has a __dict__ attribute:

# Module example
import math
print(vars(math))

# Class example
class MyClass:
    x = 5
    def __init__(self, y):
        self.y = y

obj = MyClass(10)
print(vars(obj))

The function will output a dictionary of the provided object’s attributes and their current values.

Example Output

The following image shows the result of vars() when called on a simple class instance:

vars() output example
vars() output example
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythondictionarybuilt-in functionobject attributesvars
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.