5

I am getting the following error on my production server:

Traceback (most recent call last):

 File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 89, in get_response
response = middleware_method(request)
 File "myproject/middleware.py", line 31, in process_request
if not any(m.match(path) for m in EXEMPT_URLS):

NameError: global name 'any' is not defined

The server is running python 2.6 and in development this error was not raised. The offending code is in middleware.py:

...
if not request.user.is_authenticated():
        path = request.path_info.lstrip('/')
        if not any(m.match(path) for m in EXEMPT_URLS):
            return HttpResponseRedirect(settings.LOGIN_URL)

Should I rewrite this any function to work around the problem?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
  • 7
    From the stack trace, your server appears to be running Python 2.4, which doesn't have `any`. – Michael Mior Jan 27 '12 at 17:59
  • oops. Oh yeah. Any suggestions how can I rewrite the code to be compatible with python2.4? – Darwin Tech Jan 27 '12 at 18:14
  • @Ned seems to have given a good answer. Although I would really consider upgrading if at all possible. The next version of Django (1.4) won't support Python 2.4. – Michael Mior Jan 27 '12 at 19:19

2 Answers2

11

You are actually running on Python 2.4, which doesn't have an any builtin.

If you need to define your own any, it's easy:

try:
    any
except NameError:
    def any(s):
        for v in s:
            if v:
                return True
        return False
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
3

I got this Python error as well with this line:

>>> any([False, True, False])
Error:'any' is not defined

Here's a work around without redefining the any function:

>>> [False, True, False].count(True) > 0
True

Counting the number of Trues and then asserting it is greater than 0 does the same thing as the any function. It might be slightly less efficient since it requires a full list scan rather than breaking out as soon as a True is found.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335