Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python vars() function is used to return __dict__ attribute of an object. It takes only one optional parameter. It takes an object as a parameter having __dict__ attribute like a class, an instance, or any object.

Syntax

vars(object)

Parameters

object Optional. specify an object with __dict__ attribute

Example: Object with __dict__ attribute

In the below example, the var() function is used to return __dict__ attribute of an object called MyClass.

class MyClass:
  name = 'John'
  age = 25
  city = 'London'

x = vars(MyClass)
print(x)

The output of the above code will be:

{'__doc__': None, 'name': 'John', '__module__': '__main__', 'age': 25, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, 'city': 'London'}

If the object which does not has __dict__ attribute is passed into vars() function , it will raise a TypeError exception.

Example: Object without __dict__ attribute

In the below example, the object called MyList does not have __dict__ attribute. When it is passed through vars() function, it will raise an exception.

MyList = [1, 2, 3]
x = vars(MyList)
print(x)

The output of the above code will be:

TypeError: vars() argument must have __dict__ attribute

When the vars() function is used without argument, it acts like Python locals() function.

Example: vars() function as locals() function

In the below example, the vars() function is used without argument and it behaves like locals() function.

x = vars()
print(x)

The output of the above code will be:

{'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fbd94e344e0>, '__builtins__': <module 'builtins' (built-in)>, 'sys': <module 'sys' (built-in)>, '__spec__': None, '__file__': './temp/main.py', 'x': {...}, '__name__': '__main__', '__doc__': None, '__cached__': None, '__package__': None}

❮ Python Built-in Functions