Methods and Functions

Python vars()

You might have come across the term __dict__ in Python. __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. So, how do we retrieve the value of __dict__? Python vars(), an inbuilt function is used to return the value of the __dict__ attribute.

Python vars() function

Definition

  • The Python vars() function is used to retrieve the __dict__ attribute for the specified module, class, instance, or any other object with a __dict__ attribute.

Python vars()

The Python vars() method is a part of Python’s standard library collection of built-in functions. It returns the name: value pair mappings for all names defined in the local scope or the optional object argument’s scope along with their associated values.

  • Syntax

Let us look at the syntax for the Python vars() function:

Python vars() parameters

The vars() method accepts only one parameter, which is also optional. It accepts an object as a parameter.

object = can be a module, a class, an instance, or any other object with the __dict__ attribute

Return value from vars()

  • Python vars() returns the specified object’s __dict__ attribute.
  • If the specified object passed to vars() does not have the __dict__ attribute, a TypeError exception is raised/thrown.
  • If no arguments are passed to vars(), it behaves similar to the locals() method.
  • For instance, if we change the dictionary values in the object __dict__, then the newly modified value will be returned by the vars() function.

Example: Working of Python vars()

Let us look at few examples where Python vars() is applicable and understand this inbuilt function in detail.

Example 1

                    

# Python program to illustrate vars()
class Student:
    def __init__(self, name = 'Leo', age = 22, course = 'MBA', city = 'Mumbai'):
        self.Name = name
        self.Age = age
        self.Course = course
        self.City = city

obj = Student()
print('Dictionary output is:', vars(obj))

Output

                    

Dictionary output is: {'Name': 'Leo', 'Age': 22, 'Course': 'MBA', 'City': 'Mumbai'}

Explanation

In the above example, we constructed a class called Student and created an instance called ‘obj’ of the Student class, which then uses the Python vars() function to output the __dict__ attribute of the name, age, course, and city objects.

Example 2

                    

# Python program to illustrate vars()
class Business:
   def __init__(self):
       self.Company = 'ABC Ltd'
       self.Sector = 'IT Sector'
       self.Employees = 5400
       self.Turnover = '100 crore'

obj = Business()
print(vars(obj))

Output

                    

{'Company': 'ABC Ltd', 'Sector': 'IT Sector', 
'Employees': 5400, 'Turnover': '100 crore'}

Python vars() without any arguments

Example

Output

                    

{'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, 
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

Python vars() without __dict__ attribute

If the class of the specified object does not have the dict attribute, then the vars() method throws a TypeError. Because none of the built-in classes implement it, providing built-in objects to vars() will result in an error, as illustrated below.

Example

                    

print(vars('Programming'))
# OR (returns same error)
print(vars(10))

Output

                    

Traceback (most recent call last):
File "", line 1, in 
TypeError: vars() argument must have __dict__ attribute

Frequently Asked Questions

Q1. What is vars in Python?

The Python vars() function is used to retrieve the __dict__ attribute for the specified module, class, instance, or any other object with a __dict__ attribute. It returns the name: value pair mappings for all names defined in the local scope or the optional object argument’s scope along with their associated values i.e. it returns a dictionary containing the key: value pair specified in the object.

Example

                    

class Item:
    def __init__(self, car = 'Audi', speed = '240 kmph', price = 89000):
        self.car = car
        self.speed = speed
        self.price = price

x = Item()
print('Item details:', vars(x))

Output

                    

Item details: {'car': 'Audi', 'speed': '240 kmph', 'price': 89000}

Q2. Is vars a keyword in Python?

In Python, vars is not considered as a keyword. Rather vars() is a built-in function provided by Python to compute certain functionality. Python vars() is used to return the __dict__ attribute for the specified module, class, instance, or any other object with a __dict__ attribute.

Example

                    

class Numbers:
    def __init__ (self, x = 1, y = 2, z = 3):
        self.x = x
        self.y = y
        self.z = z

obj = Numbers()
print(vars(obj))

Output

                    

{'x': 1, 'y': 2, 'z': 3}

Q3. What is Python __dict__?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__. To retrieve the __dict__ attributes of an object, we use Python’s vars() built-in function.

Q4. What is the difference between globals(), locals() and vars()?

  1. Python globals() – The globals() method returns a dictionary containing all global variables and their values. It always returns the module namespace dictionary.
  2. Python locals() – Python locals() provide the same function as globals(), but for methods. Within a method, we call locals(). locals() always returns a dictionary containing information about the current namespace.
  3. Python vars() – Internal dictionary instances/attributes (called __dict__) exist in objects such as classes, methods, instances. The vars() method can be used to retrieve this dictionary from a class instance. Python vars() returns either a dictionary of the current namespace (if no argument is passed) or the dictionary of the argument.
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.