Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Python vars() Function



The Python vars() function returns __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 example below, the var() function returns __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:

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

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 example below, 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:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    x = vars(MyList)
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 example below, 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:

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

❮ Python Built-in Functions

5