views:

64

answers:

1

This might be an isolated problem, but figured I'd ask in case someone has thoughts on a graceful approach to address it.

Here's the setup:

--------
views.py
--------
from django.http import HttpResponse
import shortcuts

def mood_dispatcher(request):
  mood = magic_function_to_guess_my_mood(request)
  return HttpResponse('Please go to %s' % shortcuts.MOODS.get(mood, somedefault))


------------
shortcuts.py
------------
MOODS = # expensive load that causes a reverse to happen

The issue is that shortcuts.py causes an exception to be thrown when a reverse is attempted before django is done building the urls. However, views.py doesn't yet need to import shortcuts.py (used only when mood_dispatcher is actually called). Obvious initial solutions are: 1) Import shortcuts inline (just not very nice stylistically) 2) Make shortcuts.py build MOODS lazily (just more work)

What I ideally would like is to be able to say, at the top of views.py, "import shortcuts except when loading urls"

A: 

Well you can do it in python, since the "import" statement is just code:

if some_conditional:
    import shortcuts

But in this case it would not be very pythonic, since shortcuts is a dependency of the function mood_dispatcher and not of the module itself, then you could do the import inside the function.

Python's import system is very flexible and powerful but you must pay attention to the import order (and also avoid circular dependencies as well).

Regards

Arthur Debert
yeah, that makes sense - probably the least ugly thing here is to just do as you said and import in the function itself.
nicknack