Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

python - getattr() versus dict lookup, which is faster?

A somewhat noobish, best practice question. I dynamically look up object attribute values using object.__dict__[some_key] as a matter of habit. Now I am wondering which is better/faster: my current habit or getattr(object,some_key). If one is better, why?

>>> class SomeObject:
...     pass
... 
>>> so = SomeObject()
>>> so.name = 'an_object'
>>> getattr(so,'name')
'an_object'
>>> so.__dict__['name']
'an_object'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...