Wednesday, 23 August 2017

Difference between anonymous function and real function

Friend asked me, whether there is any difference between an anonymous function and a real function.

There is an obvious difference that you cannot put print statements in anonymous function a.k.a lambda function

Anyway, all things being equal, I immediately felt that was  really a good question for the reason that whether two produce same byte code for the same program.

Here we will find out.



In [1]: def add(x,y):
   ...:     return x+y
   ...: 

In [2]: k = lambda x,y : x+y


In [3]: import dis

In [4]: dis.dis(add)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 BINARY_ADD          
              7 RETURN_VALUE        

In [5]: dis.dis(k)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 BINARY_ADD          
              7 RETURN_VALUE        

In [6]:

As you can see both generated byte codes, there is no difference between the two.

No comments:

Post a Comment