Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of lambda in the following expression

While going developing OpenERP, I found the following piece of code

'app_date': lambda *a: time.strftime('%Y-%m-%d')

I know what lambda is.My question is why use lambda?Why not just

'app_date': time.strftime('%Y-%m-%d')

like image 526
Jibin Avatar asked Sep 06 '12 06:09

Jibin


People also ask

What is the use of lambda expression?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

What is a lambda expression example?

Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable).

What is this in lambda expression?

The "this" and "super" references within a lambda expression are the same as in the enclosing context. Since the lambda expression doesn't define a new scope, "this" keyword within a lambda expression signifies "this" parameter of a method where the lambda expression is residing.

What is the use of lambda expression in Python?

We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.


1 Answers

'app_date': time.strftime('%Y-%m-%d') will evaluate the time.strftime immediately. By wrapping it in a lambda, its execution is deferred until later (the time when you call the lambda). Roughly speaking, the difference is between "the time when I defined this" and "the time when I am using this". Look:

>>> d = {'a': time.time(), 'b': lambda: time.time()}
>>> d['a'], d['b']()
(1346913545.049, 1346913552.409)
>>> d['a'], d['b']()
(1346913545.049, 1346913554.518)
>>> d['a'], d['b']()
(1346913545.049, 1346913566.08)

I allowed some time to elapse in between each d['a'], d['b'](). Note that d['a'] is always the same: it is the time when I defined d. d['b'] is a function. d['b']() (with parentheses) calls the function, which evaluates the time anew on each call, so it is different at each usage.

Also, this is nothing special about lambda. Lambdas are just functions like any other. I could do the same with:

def func():
    return time.time()
d = {'a': time.time(), 'b': func}
like image 61
BrenBarn Avatar answered Sep 23 '22 19:09

BrenBarn