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.
Martijn pieters
source share