What is the use of vars(), dir() and help() functions?
Last updated 3 years, 1 month ago | 1153 views 75 5

Python | vars(), dir() and help()
- The vars() function returns the __dict__ attribute of an object.
- The dir() function returns all properties and methods of the specified object, without the values.
- The help() function is used to display the documentation string and also facilitates us to see the help related to modules, keywords, and attributes.
vars()
The vars() function is part of the standard library in Python and is used to get an object’s _dict_ attribute. The returned _dict_ attribute contains the changeable attributes of the object. This means that when we update the attribute list of an object, the var() function will return the updated dictionary.
class Student:
name = "John"
age = 36
country = "Norway"
print(vars(Student))
# Output
mappingproxy({'__module__': '__main__', 'name': 'John', 'age': 36, 'country': 'Norway', '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None})
dir()
The dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.
- For Modules/Library objects, it returns a list of all attributes, contained in that module.
- For Class Objects, it returns a list of all valid attributes and base attributes.
- With no arguments passed, it returns a list of attributes in the current scope.
class Student:
name = "John"
age = 36
country = "Norway"
print(dir(Student))
# Output
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'country', 'name']
help()
The help() method calls the built-in Python help system. It is used to display the documentation string and also facilitates us to see the help related to modules, keywords, and attributes.
class Student:
name = "John"
age = 36
country = "Norway"
print(help(Student))
# Output
Help on class Student in module __main__:
class Student(builtins.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| age = 36
|
| country = 'norway'
|
| name = 'John'