Use `__dict__` or `vars()`?

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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')

Solution 2 - Python

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.

Solution 3 - Python

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn McGeheeView Question on Stackoverflow
Solution 1 - PythonMatthew TrevorView Answer on Stackoverflow
Solution 2 - PythoniljauView Answer on Stackoverflow
Solution 3 - PythonmaxView Answer on Stackoverflow