[英]dict.get(key, default) vs dict.get(key) or default
Is there any difference (performance or otherwise) between the following two statements in Python? Python中的以下两个语句之间有什么区别(性能或其他)?
v = my_dict.get(key, some_default)
vs对比
v = my_dict.get(key) or some_default
There is a huge difference if your value is false-y :如果您的值是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.你不应该使用
or default
,如果您的值可以是假的-Y。
On top of that, using or
adds additional bytecode;最重要的是,使用
or
添加额外的字节码; a test and jump has to be performed.必须执行测试和跳转。 Just use
dict.get()
, there is no advantage to using or default
here.只需使用
dict.get()
,在这里使用or default
没有优势。
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.还有另一个区别:如果
some_default
不是值而是表达式,则必须在传递给dict.get()
之前对其进行评估,而如果您从字典中获得真值,则不会评估 with or
表达式。 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.因此,虽然它确实不安全,
or
您的字典可能包含假值,但可能会带来性能优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.