1

I find the documentation on the vars() function to be kind of cryptic: https://docs.python.org/3/library/functions.html#vars

What is the point of having this function? Why would you not just call x.__dict__ rather than vars(x) or locals() directly?

Would someone give a use case of the function?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Allen Wang
  • 2,426
  • 2
  • 24
  • 48

2 Answers2

8

The point of having the vars() function is:

  • you do not need to touch the classes __dict__ dunder function directly from the outside

It is the same with most __dunders__:

next()  => __next__  
>=      => __ge__
<=      => __le__
str()   => __str__
repr()  => __repr__

See: Python datamodel __lt__ etc.

See also: Should I ever directly call object.__str__()?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    it's focus on more readable and clean code right ? – sahasrara62 Jan 04 '19 at 22:57
  • 1
    @prashantrana and encapsulation. The "normal" methods can have logic that calling the dunder directly would not have – Patrick Artner Jan 04 '19 at 22:59
  • @PatrickArtner could you give an example of this type of logic? It seems here that vars() doesn't have any additional logic? – Allen Wang Jan 04 '19 at 23:36
  • 1
    @AllenWang wait for python 3.7 / 3.8 ... maybe it will have it then - maybe some other dunder gets introduced that i also checked by next() as fallback - if you cann `__dict__` directly you wont get that added functionality – Patrick Artner Jan 04 '19 at 23:38
0

The python builtin vars(object) function returns the __dict__ attribute of the object in the parentheses; if not applicable, it gives a TypeError exception. It should be used to view dictionaries.

When you run:

# Python program to illustrate 
# working of vars() method in Python 

class Example: 
def __init__(self, name1 = "Bob", num2 = 100, name3 = "Bill"): 
    self.name1 = name1 
    self.num2 = num2 
    self.name3 = name3 

exampleVariable = Example()
print(vars(exampleVariable)) 

The output is:

{'num2': 100, 'name1': 'Bob', 'name3': 'Bill'}
Arnav Poddar
  • 354
  • 2
  • 18