dict.get(key, default) vs dict.get(key) or default

江枫思渺然 提交于 2020-05-09 06:11:21

问题


Is there any difference (performance or otherwise) between the following two statements in Python?

v = my_dict.get(key, some_default)

vs

v = my_dict.get(key) or some_default

回答1:


There is a huge difference if your value is false-y:

>>> d = {'foo': 0}
>>> d.get('foo', 'bar')
0
>>> d.get('foo') or 'bar'
'bar'

You should not use or default if your values can be false-y.

On top of that, using or adds additional bytecode; a test and jump has to be performed. Just use dict.get(), there is no advantage to using or default here.




回答2:


There is another difference: if some_default is not a value but an expression, it must be evaluated before being passed to dict.get(), whereas with or the expression will not be evaluated if you get a truthy value out of your dictionary. For example:

v = my_dict.get(key, do_something_that_takes_a_long_time())  # function always called
v = my_dict.get(key) or do_something_that_takes_a_long_time()  # function only called if needed

So while it is true that it isn't safe to use or if your dictionary can contain falsey values, there can potentially be a performance advantage.



来源:https://stackoverflow.com/questions/33263623/dict-getkey-default-vs-dict-getkey-or-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!