Lambdas in ternary operator unexpected behavior

45 views Asked by At
>>> (lambda: 1 if True else lambda: 2)()
1
>>> (lambda: 1 if False else lambda: 2)()
<function <lambda>.<locals>.<lambda> at 0x7f5772e8eef0>
>>> (lambda: 1 if False else lambda: 2)()()
2

Why does it require calling the latter one twice?

Thanks.

2

There are 2 answers

0
blubberdiblub On BEST ANSWER

Writing it like lambda: 1 if condition else lambda: 2 will have it interpreted like this:

lambda: (1 if condition else lambda: 2)

You need to write it like this in order for it to work as intended:

(lambda: 1) if condition else lambda: 2
0
rdas On
lambda: 1 if False else lambda: 2

Let me write this as a normal function with if-statements:

def func():
    if False:
        return 1
    else:
        return (lambda: 2)

Now if I do:

x = func()

x will be lambda: 2 - which is another function.

So how do I get to the 2?

x()

This gives:

2

Now if I in-line the variable x:

res = func()()

Now res will be 2

I hope that was clear. That's why the two () was required.

You probably wanted something like this:

(lambda: 1) if False else (lambda: 2)

Which is just a normal if-statement returning functions.