vars() function in Python
Last Updated :
13 Nov, 2023
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
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. Pythonarr = [1, 5, 2] print(sum(arr))Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything list , tuples or dict
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.Pythonage = "21" print("age =", int(age)
3 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(sta
6 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:Pythons = "GeeksforGeeks" # G
2 min read
Python str() function The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Letâs take a simple example to converting an Intege
3 min read
dir() function in Python The dir() function is a built-in Python tool used to list the attributes (like methods, variables, etc.) of an object. It helps inspect modules, classes, functions, and even user-defined objects during development and debugging.Syntaxdir([object])Parameters: object (optional): Any Python object (lik
3 min read
Python Inner Functions In Python, a function inside another function is called an inner function or nested function. Inner functions help in organizing code, improving readability and maintaining encapsulation. They can access variables from the outer function, making them useful for implementing closures and function dec
5 min read