getattr() versus __dict__ lookup, which is faster?
Asked Answered
W

1

18

I can dynamically look up object attribute values using object.__dict__[some_key] or getattr(object, some_key). Which is faster or better, and why?

>>> class SomeObject:
...     pass
... 
>>> so = SomeObject()
>>> so.name = 'an_object'
>>> getattr(so,'name')
'an_object'
>>> so.__dict__['name']
'an_object'
Wardroom answered 29/12, 2012 at 18:56 Comment(0)
C
52

You are much better off using getattr() instead of going directly to the __dict__ structure.

Not because it's faster or slower, but because the official API works in all circumstances, including for classes that do not have a __dict__ (when using __slots__ for example), or when an object implements the __getattr__ or __getattribute__ hooks, or when the attribute in question is a descriptor (such as a property), or a class attribute.

If you want to know if any one python statement or technique is faster than another, 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 directly accessing __dict__ is faster, but getattr() does a lot more work.

Chen answered 29/12, 2012 at 18:58 Comment(1)
getattr also respects the MRO and descriptors (common example: properties).Wrinkle

© 2022 - 2024 — McMap. All rights reserved.