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.

6
  • Your code works fine for me in the Django 1.6.1 console (after adding a missing bracket). Commented Apr 17, 2014 at 12:56
  • Not working for me. I am using django 1.4 with python 2.7. Commented Apr 17, 2014 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. Commented Apr 17, 2014 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 Commented Apr 17, 2014 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). Commented Apr 17, 2014 at 15:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was trying it in shell only and never realized that it could be an error in shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.