Anonymous function assignment using 1 line operator

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?

+5
source share
1 answer

lambda has weaker binding than conditional expression. In fact, it has the lowest operator priority in the language. From the documentation 1 :

enter image description here

So this line:

 fn = lambda x: x if True else lambda x: x*x 

Python is actually interpreted as:

 fn = lambda x: (x if True else lambda x: x*x) 

To do what you want, you need to add brackets:

 fn = (lambda x: x) if True else (lambda x: x*x) 

1 Note that the table is ordered from smallest to largest.

+11
source

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


All Articles