Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is vars() in Python?

Mahnoor Zaheer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The vars() method is a built-in Python function that returns the __dict__ attribute of an object.

Syntax

The syntax for the vars() method is as follows:

vars(object)
The syntax of the vars() method in Python

Parameters

The vars() method only takes one required parameter, which is an object. The object can be a class, module, instance, etc.

Return value

The return value is the __dict__ attribute. However, if the object does not have any such attribute, the function raises a TypeError.

Example

In the code below, the vars() function returns the key-value pair of the class object in the first case.

Note: When an argument with no __dict__ attribute is passed into the vars() function, the function gives an error.

# dict attribute present
class School:
def __init__(self, section1 = 55, section2 = 73):
self.x = section1
self.y = section2
object = School()
print('Class object:', vars(object))
# dict attribute absent
print('List object', vars([1,2,3]))
The syntax of the vars() method in Python

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring