Why do we need parentheses around lambda functions when assigning them to variables?

I just stumbled upon some unexpected behavior in Python in the code snippet below

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"])))

Output signal

<function <lambda>.<locals>.<lambda> at 0x7f7e5eeed048>
True

However, when adding brackets around the lambda, everything works as expected:

func_1 = (lambda x,y:set([x]) == y) if b else (lambda x,y: x in y)
# ...

Then the conclusion will be

True
True

Why do I need these brackets? I thought the initial expression is equivalent to the long if-else construct.

+4
source share
1 answer

These are just standard priority rules. Your first expression is parsed as:

lambda x,y:set([x]) == (y if b else lambda x,y: x in y)

So you need to add parentheses to create the correct priority.

+5
source

Source: https://habr.com/ru/post/1664271/


All Articles