Getattr () versus dict lookup, which is faster?

A few nubes, a question with best practice. I dynamically look at the attribute values ​​of an object using object.__dict__[some_key] as a rule. Now I wonder what is better / faster: my current habit or getattr(object,some_key) . If better, why?

 >>> class SomeObject: ... pass ... >>> so = SomeObject() >>> so.name = 'an_object' >>> getattr(so,'name') 'an_object' >>> so.__dict__['name'] 'an_object' 
+7
source share
1 answer

You are much more comfortable using getattr() instead of directly navigating to the __dict__ structure.

Not because this happens faster or slower, but because the official API works in all circumstances, including for classes that don't have __dict__ (when using __slots__ ), or when an object implements __getattr__ or __getattribute__ , or when the attribute in question is descriptor (e.g. property ) or class attribute.

If you want to find out if any one python statement or method is faster than the other, use the timeit module to measure the difference:

 >>> import timeit >>> class Foo(object): ... pass ... >>> foo = Foo() >>> foo.bar = 'spam' >>> timeit.timeit("getattr(foo, 'bar')", 'from __main__ import foo') 0.2125859260559082 >>> timeit.timeit("foo.__dict__['bar']", 'from __main__ import foo') 0.1328279972076416 

You can see that direct access to __dict__ is faster, but getattr() works a lot more.

+35
source

All Articles