Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use `__dict__` or `vars()`?

Tags:

python

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?

like image 356
John McGehee Avatar asked Jan 23 '14 00:01

John McGehee


People also ask

What is the __ dict __ of a class and or instance of a class and what does it contain?

It's a data descriptor object that returns the internal dictionary of attributes for the specific instance.

What is the use of __ dict __ in Python?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.

What is self __ dict __?

__dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined for the object.

What is Vars Python?

Python vars() Function The vars() function returns the __dic__ attribute of an object. The __dict__ attribute is a dictionary containing the object's changeable attributes. Note: calling the vars() function without parameters will return a dictionary containing the local symbol table.


2 Answers

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.

like image 32
iljau Avatar answered Oct 03 '22 23:10

iljau


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

like image 111
Matthew Trevor Avatar answered Oct 04 '22 00:10

Matthew Trevor