Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
set() Function in python
Next article icon

vars() function in Python

Last Updated : 13 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be a module, a class, an instance, or access the __dict__ attribute in Python. In this article, we will learn more about vars() function in Python.

Python vars() Function Syntax 

Syntax: vars(object)

Parameters

  • object – can be a module, class, instance, or any object having the __dict__ attribute

Return

  • __dict__ attribute of the given object.
  • methods in the local scope when no arguments are passed
  • TypeError: if the object passed doesn’t have the __dict__ attribute

vars() Function in Python

The method returns the __dict__ attribute for a module, class, instance, or any other object if the same has a __dict__ attribute. If the object fails to match the attribute, it raises a TypeError exception. Objects such as modules and instances have an updatable __dict__ attribute however, other objects may have written restrictions on their __dict__ attributes. vars() acts like the locals() method when an empty argument is passed which implies that the local dictionary is only useful for reads since updates to the local dictionary are ignored. 

How vars() Function in Python works?

In the given code, we are creating a class Geeks and we have created three attributes. We have created an object of class Geeks() and we printed the dict with vars() function in Python.

Python3




class Geeks:
  def __init__(self, name1 = "Arun",
               num2 = 46, name3 = "Rishab"):
    self.name1 = name1
    self.num2 = num2
    self.name3 = name3
 
GeeksforGeeks = Geeks()
print(vars(GeeksforGeeks))
 
 

Output

{'name1': 'Arun', 'num2': 46, 'name3': 'Rishab'}

Python vars() without any Arguments

In this example, we are using vars() without any arguments.

Python3




# vars() with no argument
print (vars())
 
 

Output

{'__name__': '__main__', '__doc__': None, '__package__': None,

'__loader__': <class '_frozen_importlib.BuiltinImporter'>,

'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

Python vars() with Custom Object

In the given example, we have defined the Geeks class with methods loc(), code(), and prog(). The loc() method returns local variables using locals(), code() returns object attributes using vars(), and prog() returns class attributes using vars(self). 

Python3




class Geeks(object):
    def __init__(self):
        self.num1 = 20
        self.num2 = "this is returned"
 
    def __repr__(self):
        return "Geeks() is returned"
 
    def loc(self):
        ans = 21
        return locals()
     
    # Works same as locals()
    def code(self):
        ans = 10
        return vars()
 
    def prog(self):
        ans = "this is not printed"
        return vars(self)
     
 
if __name__ == "__main__":
    obj = Geeks()
    print (obj.loc())
    print (obj.code())
    print (obj.prog())
 
 
Output
{'self': Geeks() is returned, 'ans': 21} {'self': Geeks() is returned, 'ans': 10} {'num1': 20, 'num2': 'this is returned'}        

Python vars() without __dict__ Attribute

In the given example, we have attributes that are not dict that’s why when we used the var() method, it shows a type error.

Python3




print(vars('Geeks for geeks'))
print(vars(123.45))
 
 

Output

TypeError: vars() argument must have __dict__ attribute


Next Article
set() Function in python
author
chinmoy lenka
Improve
Article Tags :
  • Python
  • python
  • Python-Built-in-functions
Practice Tags :
  • python
  • python

Similar Reads

  • sum() function in Python
    The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. [GFGTABS] Python arr = [1, 5, 2] print(sum(arr)) [/GFGTABS]Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything
    3 min read
  • set() Function in python
    set() function in Python is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning elements can be added or removed after creation. However, all elements inside a set must be immutable, such as numbers, strings or tuples. The set() function can take an i
    3 min read
  • Python int() Function
    The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part. Example: In this example, we passed a string as an argument to the int() function and printed it. [GFGTABS] Python age = "21"
    4 min read
  • round() function in Python
    Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
    6 min read
  • type() function in Python
    The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
    5 min read
  • Python print() function
    The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
    2 min read
  • randint() Function in Python
    randint() is an inbuilt function of the random module in Python3. The random module gives access to various useful functions one of them being able to generate random numbers, which is randint(). In this article, we will learn about randint in Python. Python randint() Method SyntaxSyntax: randint(st
    6 min read
  • id() function in Python
    In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
    3 min read
  • Python input() Function
    Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax:  input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
    4 min read
  • Python len() Function
    The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example: [GFGTABS] Python s = "G
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences