Using lambda in the following expression

When developing OpenERP, I found the following code snippet

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

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

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

+5
source share
1 answer

'app_date': time.strftime('%Y-%m-%d')will evaluate immediately time.strftime. By packing it into a lambda, its execution is delayed until a later time (the time when you call the lambda). Roughly speaking, the difference is between "time when I defined this" and "time when I use this." Take a 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)

, d['a'], d['b'](). , d['a'] : , d. d['b'] - . d['b']() ( ) , , .

, lambda. - , . :

def func():
    return time.time()
d = {'a': time.time(), 'b': func}
+13

All Articles