简体   繁体   中英

Using an imported function inside lambda - Python

I am trying to create a timedelta dictionary based on different parameters. For eg.

from django.utils import timezone
a = {'Minutes':(lambda dt,delta: dt + timezone.timedelta(minutes=delta)),
     'Hours': (lambda dt,delta: dt + timezone.timedelta(hours=delta)}

Now while using the above dictionary:

new_time = a['Minutes'](timezone.now(),10)

It gives following error:

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <lambda>(dt, delta)
----> 1 a = {'Minutes':(lambda dt,delta: dt + timezone.timedelta(minutes=delta))}
NameError: global name 'timezone' is not defined

Please explain why I cannot use the imported function inside lambda.

Reference here: https://code.djangoproject.com/ticket/18204

(fixed in Django 1.6)

see also:
https://stackoverflow.com/a/19004592/202168
https://github.com/ipython/ipython/issues/2532/

I posted this here because I quite often run into this issue (and the couple of comments seemed to be shell-related), although the OP has not stated they are in the Django shell at all so this answer could be irrelevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM