vars()

The built-in vars() function returns the .__dict__ attribute for a module, class, instance, or any other object with this attribute. This attribute is a dictionary that represents the object’s namespace, mapping attribute names to their values:

Python
>>> class Point:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...

>>> point = Point(10, 20)
>>> vars(point)
{'x': 10, 'y': 20}

vars() Signatures

Python Syntax
vars()
vars(object)

Arguments

Argument Description
object An object with a .__dict__ attribute

Return Value

  • When an object with a .__dict__ attribute is provided, vars() returns a dictionary representing the object’s namespace.
  • Without an argument, it returns a dictionary of the local namespace similar to locals().

vars() Examples

With a class instance as an argument:

Python
>>> class Rectangle:
...     def __init__(self, length, width):
...         self.length = length
...         self.width = width
...

>>> rect = Rectangle(3, 4)
>>> vars(rect)
{'length': 3, 'width': 4}

With a module object:

Python
>>> import sys
>>> vars(sys)
{'__name__': 'sys', ..., 'ps1': '>>> ', 'ps2': '... '}

Without any argument, acting like the locals() function:

Python
>>> a = 5
>>> b = 10
>>> vars()
{'__name__': '__main__', ..., 'a': 5, 'b': 10}

vars() Common Use Cases

The most common use cases for the vars() function include:

  • Inspecting the attributes of an object dynamically
  • Debugging by examining the current namespace
  • Interacting with module-level or class-level namespaces

vars() Real-World Example

Suppose you have a configuration class that holds various settings for an application. You can use vars() to convert the settings into a dictionary for serialization or logging:

Python
>>> class Config:
...     def __init__(self, debug=False, version='1.0'):
...         self.debug = debug
...         self.version = version
...

>>> config = Config(debug=True)
>>> config_dict = vars(config)
>>> config_dict
{'debug': True, 'version': '1.0'}

In this example, vars() helps convert an object’s attributes into a dictionary, which can then be serialized to JSON or logged for debugging purposes.

Tutorial

Namespaces and Scope in Python

In this tutorial, you'll learn about Python namespaces, the structures used to store and organize the symbolic names created during execution of a Python program. You'll learn when namespaces are created, how they are implemented, and how they define variable scope.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader