GGG
GGG

Reputation: 397

Lambdas in ternary operator unexpected behavior

>>> (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.

Upvotes: 0

Views: 44

Answers (2)

rdas
rdas

Reputation: 21285

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.

Upvotes: 0

blubberdiblub
blubberdiblub

Reputation: 4135

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

Upvotes: 3

Related Questions