When assigning a variable to an anonymous function using the single-line if statement, the else case does not behave as expected. Instead of assigning an anonymous function specified after "else", another anonymous function is assigned. This function returns the expected anonymous function.
>> fn = lambda x: x if True else lambda x: x*x >> fn(2) 2 >> fn = lambda x: x if False else lambda x: x*x >> fn(2) <function <lambda> at 0x10086dc08> >> fn('foo')(2) 4
It seems that what happens is that lambda x: x if False else lambda x: x*x generally returns as an anonymous function in the case of "else". I was able to achieve the desired behavior using the following:
>> fn = (lambda x: x*x, lambda x: x)[True] >> fn(2) 2 >> fn = (lambda x: x*x, lambda x: x)[False] >> fn(2) 4
However, I would still like to get the bottom of this unusual behavior. Any thoughts?
source share