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__.
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:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
