What is the difference between these two lines?

function1 = lambda x: function2(x) function1 = function2 

In particular, in the textbook of Tariq Rashid on writing neural networks the following version of the description of the activation function is proposed.

 self.activation = lambda x: scipy.special.expit(x) 
  • Well, in the first case, you create a new function - Cyril Malyshev
  • And function2 is what? If function2 has two required arguments, then function1 from the first line will not work at all - andreymal
  • @andreymal, function2 has 1 argument - Maxim Faleev
  • And tomorrow there will be a second one, and the first option will eventually break. Well, or the other way round. It all depends on where, how and why you use it all - andreymal
  • The scipy.special.expit function can take two arguments, although it is not explicitly stated in the documentation (and with a strong desire even three, but the third will be named, not positional) - andreymal

1 answer 1

About this very much is written everywhere. And it all comes down to the fact that functions in python are objects of the first order. It is important for us that functions are objects (like almost everything in python), that is, in addition to defining a function as such, it can be accessed by reference .

In your case:

 function1 = lambda x: function2(x) 

Equivalent to the definition of a new function through the operator def :

 def function1(x): return function2(x) 

That is, you are creating a new function using the lambda inline function. Despite the fact that this is in general a working example, it is not recommended to be used for an explicit (explicit) definition of a function for obvious reasons.

In the second case:

 function1 = function2 

you kind of create a shortcut to function2 with the name function1 , referring to the latter by reference ( reference ). In this case, in fact, function1 calls function2 and and returns the result obtained from it.

Such a system of work by reference with functions in python allows you to quite flexibly with them. For example (Dan Bader):

 >>> def myfunc(a, b): return a + b >>> funcs = [myfunc] >>> funcs[0] <function myfunc at 0x107012230> >>> funcs[0](2, 3) 5