When I assign anonymous function to the variable using ternary operator with the true condition, I can call the variable as a normal function.
JavaScript
x
4
1
>>> a = lambda x, y: x + y if True else lambda x, y: x * y
2
>>> a(1, 2)
3
3
4
But when the condition is false and the function to be assigned is after the word else
, I get something like this. I have no idea what mechanisms stand behind such a weird behaviour. Is there any syntax nuances? Or any possibility to use ternary operator in cases like this one?
JavaScript
1
4
1
>>> a = lambda x, y: x + y if False else lambda x, y: x * y
2
>>> a(1, 2)
3
<function <lambda>.<locals>.<lambda> at 0x10916aee0>
4
Advertisement
Answer
You need to use parentheses to indicate your meaning.
You mean
JavaScript
1
3
1
(lambda x, y: x + y) if True
2
else (lambda x, y: x * y)
3
but you have
JavaScript
1
4
1
lambda x, y:
2
(x + y if True
3
else lambda x, y: x * y)
4
The ... if ... else ...
operator has higher precedence than lambda
. See https://docs.python.org/3/reference/expressions.html#operator-precedence.