简体   繁体   中英

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

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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM