问题
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