1.

Give a brief comparison of vars() and dir() built-in functions in Python’s standard library.

Answer»

The vars() function can be operated upon those objects which have __dict__ attribute. It returns the __dict__ attribute for a module, class, instance, or any other object having a __dict__ attribute. If the object doesn’t have the attribute, it raises a TypeError exception. 

The dir() function returns list of the attributes of any Python object. If no parameters are passed it returns a list of names in the current local scope.  For a class , it returns a list of its attributes as WELL as those of the base classes RECURSIVELY. For a module, a list of names of all the attributes, contained is returned.

When you access an object's attribute using the dot OPERATOR, python does a lot more than just LOOKING up the attribute in that objects dictionary.

Let us take a look at the following class:

class myclass:     def __init__(self):         self.x=10     def disp(self):         print (self.x)

The vars() of above class is similar to its __dict__  value

>>> vars(myclass) mappingproxy({'__module__': '__main__', '__init__': <function myclass.__init__ at 0x7f770e520950>, 'disp': <function myclass.disp at 0x7f770e5208c8>, '__dict__': <attribute '__dict__' of 'myclass' objects>, '__weakref__': <attribute '__weakref__' of 'myclass' objects>, '__doc__': None}) >>> myclass.__dict__ mappingproxy({'__module__': '__main__', '__init__': <function myclass.__init__ at 0x7f770e520950>, 'disp': <function myclass.disp at 0x7f770e5208c8>, '__dict__': <attribute '__dict__' of 'myclass' objects>, '__weakref__': <attribute '__weakref__' of 'myclass' objects>, '__doc__': None})

However, vars() of its object just shows instance attributes

>>> a=myclass() >>> vars(a) {'x': 10} >>> x.__dict__ {'x': 10}

The dir() function returns the attributes and methods of myclass as well as object class, the base class of all Python classes.

>>> dir(myclass) ['__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__', 'disp']

Whereas dir(a), the object of myclass returns instance variables of the object, methods of its class and object base class

>>> a=myclass() >>> dir(a) ['__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__', 'disp', 'x']


Discussion

No Comment Found