2

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.

Anuj
  • 1,160
  • 2
  • 20
  • 40
  • Your code works fine for me in the Django 1.6.1 console (after adding a missing bracket). – mbatchkarov Apr 17 '14 at 12:56
  • Not working for me. I am using django 1.4 with python 2.7. – Anuj Apr 17 '14 at 12:58
  • 3
    Are you using `a` in the same module where you imported `django.utils.timezone`? Name lookups in the body of a lambda occur when the function is called, not defined. – chepner Apr 17 '14 at 13:09
  • @Anuj this is effectively a bug in the Django `./manage.py shell` ...it does something funny with the ipython context. This has been fixed in recent versions of Django. If I can find the reference I'll post as an answer. there was a bug ticket on Django about it – Anentropic Apr 17 '14 at 13:25
  • @chepner Do you have any citation to back your lambda name visibility claim? Empirical evidence points that lambdas see the context in which they were defined (like regular functions), not the one where they're called (in both 2.7.5 and 3.3.0). – lanzz Apr 17 '14 at 15:18
  • Regular functions also defer lookups until they are called. The scope of where that lookup occurs, of course, is fixed at the time the function is defined. In either case, `timezone` needs to exist when the lambda is called, not when it is defined. – chepner Apr 17 '14 at 15:29

1 Answers1

5

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.

Community
  • 1
  • 1
Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • 1
    I was trying it in shell only and never realized that it could be an error in shell. – Anuj Apr 18 '14 at 04:21