Python vars()

The vars() method returns the __dict__ (dictionary mapping) attribute of the given object.

Example


vars() Syntax

The syntax of the vars() method is:

vars(object)

vars() Parameter

The vars() method takes a single parameter:

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

vars() Return Value

The vars() method returns:

  • __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

Example: Python vars()

Output:

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

{'__repr__': <slot wrapper '__repr__' of 'dict' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'dict' objects> ….}

Example 2 : vars() with No __dict__ Attribute Argument

Output:

TypeError: vars() argument must have __dict__ attribute

In the above example, we have passed a string "Jones" to the vars() method.

Since a string doesn't have the __dict__ attribute, we get a TypeError.


Example 3: vars() with a custom object

Output

{'apple': 5, 'banana': 10}

In the above example, we have used the vars() method with a custom object eat of the class Fruit.

As you can see, there are two variables in the Fruit class apple and banana with their values 5 and 10.

Hence, we get the output {'apple': 5, 'banana': 10} in a dictionary form thanks to the vars() method.


Recommended Readings: