[英]Why do I need brackets around lambda functions when assigning them to variables?
I've just stumbled about some unexpected behavior in Python in the below code snippet 我刚刚在下面的代码片段中偶然发现了Python中的一些意外行为
b = False
func_1 = lambda x,y:set([x]) == y if b else lambda x,y: x in y
func_2 = None
if not b:
func_2 = lambda x,y : x in y
else:
func_2 = lambda x,y:set([x]) == y
print(func_1("Hello", set(["Hello", "World"])))
print(func_2("Hello", set(["Hello", "World"])))
The output is 输出是
<function <lambda>.<locals>.<lambda> at 0x7f7e5eeed048>
True
However, when adding brackets around the lambdas everything works as expected: 但是,当在lambdas周围添加括号时,一切都按预期工作:
func_1 = (lambda x,y:set([x]) == y) if b else (lambda x,y: x in y)
# ...
The output then is 输出然后是
True
True
Why do I need those brackets? 为什么我需要这些括号? I thought the initial expression was equivalent to the long if-else construct.
我认为初始表达式等同于长if-else结构。
It's just standard precedence rules. 这只是标准的优先规则。 Your first expression is being parsed as:
您的第一个表达式被解析为:
lambda x,y:set([x]) == (y if b else lambda x,y: x in y)
So you need to add the parentheses to create the correct precedence. 因此,您需要添加括号以创建正确的优先级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.