75

Builtin function vars() looks more Pythonic to me, but I see __dict__ used more frequently.

The Python documentation indicates that they are equivalent.

One blogger claims that __dict__ is faster than vars().

Which shall I use?

John McGehee
  • 9,117
  • 9
  • 42
  • 50
  • 1
    It depends what you're trying to do. In many cases, neither approach is the Right Way. In this broad a question, it seems that both work fine. – Adam Smith Jan 23 '14 at 00:49
  • 2
    I generally go with `__dict__` just to avoid another layer of parentheses. Flat is better than nested and all. – user2357112 Jan 23 '14 at 00:50
  • I guess `__dict__` being slightly faster is no surprise. Accessing object attributes is faster than calling a function. – aIKid Jan 23 '14 at 00:58
  • 1
    I don't know why but using `vars` seems cooler, and a little more neat. I can imagine this is more useful for beginners. It would be easier to explain, "Getting the vars of an object". – aIKid Jan 23 '14 at 00:59
  • To me `__dict__` is more intuitive because I get back `dict` representation of an object. – Akavall Oct 06 '17 at 17:55

3 Answers3

82

Generally, you should consider dunder/magic methods to be the implementation and invoking functions/methods as the API, so it would be preferable to use vars() over __dict__, in the same way that you would do len(a_list) and not a_list.__len__(), or a_dict["key"] rather than a_dict.__getitem__('key')

Matthew Trevor
  • 14,354
  • 6
  • 37
  • 50
35

I'd use vars().

From: https://wiki.python.org/moin/DubiousPython#Premature_Optimization

While a correctly applied optimization can indeed speed up code, optimizing code that is only seldom use [..] can make code harder to read. [..] Write correct code first, then make it fast (if necessary).

From: The Zen of Python

Readability counts.

iljau
  • 2,151
  • 3
  • 22
  • 45
22

I agree vars should be preferred. My rationale is that, as python evolves, vars might be extended to do more than __dict__ does (for example, work for objects with slots, possibly in 3.7).

max
  • 49,282
  • 56
  • 208
  • 355