Python vars()

In this post, we will see about vars() method.
Python var() method returns __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.


If you pass object to vars, it returns __dict__(writable) attrubute of the class.If you do not pass any attribute to vars, it acts as locals.
Please note that __dict__ is mapping object which stores class’s writable attributes.


It returns __dict__(writable) attribute of the class.If no attribute is present then it raises TypeError.


Let’s understand with help of simple example:

class Country: def __init__(self,name = 'India', population = 10000): self.population=population country = Country() print(vars(country))


{‘name’: ‘India’, ‘population’: 10000}

Let’s try vars function on list.

l={1,2,3,4} print(vars(l))


TypeError Traceback (most recent call last)
in ()
1 l={1,2,3,4}
—-> 2 print(vars(l))

TypeError: vars() argument must have __dict__ attribute

As you can see, we are getting TypeError in case of list.

Leave a Reply

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