Python vars() Function



The Python vars() function is a built-in function that returns the __dict__ attribute of the associated object. This attribute is a dictionary containing all the mutable attributes of the object. We can also say this function is a way of accessing the attributes of the object in a dictionary format.

If we call the vars() function without any argument, it acts similarly to the "locals()" function and will return a dictionary containing the local symbol table.

Always remember, each Python program has a symbol table that contains information about the names (variables, functions, classes, etc.) defined in the program.

Syntax

The syntax of the Python vars() function is as follows −

vars(object)

Parameters

The Python vars() function accepts a single parameter −

  • object − This parameter represents an object with __dict__ attribute. It could be a module, a class, or an instance.

Return Value

The Python vars() function returns the __dict__ attribute of the specified size. If no arguments are passed, it will return the local symbol table. And, if the passed object does not support __dict__ attribute, it raises TypeError exception.

Examples

Let's understand how vars() function works with the help of some examples −

Example 1

On applying the vars() function on a user-defined class, it returns the attributes of that class. In the following example, we have defined a class and a method with three attributes. And, we are displaying them using vars() function.

class Vehicle:
   def __init__(self, types, company, model):
      self.types = types
      self.company = company
      self.model = model
        
vehicles = Vehicle("Car", "Tata", "Safari")
print("The attributes of the Vehicle class: ")
print(vars(vehicles))

When we run above program, it produces the following result −

The attributes of the Vehicle class: 
{'types': 'Car', 'company': 'Tata', 'model': 'Safari'}

Example 2

If we use the vars() function with a built-in module, it will display the description of that module. In the code below, we are importing the string method and with the help of vars(), we list the detailed description of this module.

import string
attr = vars(string)
print("The attributes of the string module: ", attr)

Following is an output of the above code −

The attributes of the string module:  {'__name__': 'string', '__doc__': 'A collection of string constants......}

Example 3

In the following example, we have created a user-defined method named "newFun", and tried to display its attributes using vars() function.

def newFun():
   val1 = 10
   val2 = 20
   print(vars())

print("The attributes of the defined function:")
newFun()

Output of the above code is as follows −

The attributes of the defined function:
{'val1': 10, 'val2': 20}
python_built_in_functions.htm
Advertisements