Python vars()

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

Example

# returns __dict__ of a list
print(vars(list))

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

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()

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

# returns __dict__  of a dictionary object
print(vars(dict))

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

string = "Jones"

# vars() with a string
print(vars(string))

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

class Fruit:
  def __init__(self, apple = 5, banana = 10):
    self.apple = apple
    self.banana = banana
  
eat = Fruit()

# returns __dict__ of the eat object print(vars(eat))

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.


Also Read:

Did you find this article helpful?