views:

52

answers:

3

I am working with Django and use Django shell all the time. The annoying part is that while the Django server reloads on code changes, the shell does not, so every time I make a change to a method I am testing, I need to quit the shell and restart it, re-import all the modules I need, reinitialize all the variables I need etc. While iPython history saves a lot of typing on this, this is still a pain. Is there a way to make django shell auto-reload, the same way django development server does?

I know about reload(), but I import a lot of models and generally use from app.models import * syntax, so reload() is not much help.

A: 

I have tried following code. It's not working but I assume that it's close to working one. If anyone have idea how to improve it, please do.

EDIT Following code works, but I don't know why I have to exclude project from reloading. I don't feel very strong with Python importing/reloading )-:

import sys
MY_CODE_PATHS = ['/home/tomwys/dev/some_project/repository']
EXCLUDE = ['my_project_name']
def reload_all():
    for _, module in sys.modules.items():
       for path in MY_CODE_PATHS:
           if hasattr(module, '__file__') and module.__file__.startswith(path) and module.__name__ not in EXCLUDE:
               print "reloading %s" % module.__name__
               reload(module)
Tomasz Wysocki
Trying to reload individual modules is dangerous. You'll end up with stale class instances and module references, due to reloading modules but not all of their dependants, which will lead to confusing and irrelevant bugs when you're trying to test code. Unless you're testing code that you're sure is entirely localized, you should restart the whole shell.
Glenn Maynard
A: 

Reload() doesn't work in Django shell without some tricks. You can check this thread na and my answer specifically:

http://stackoverflow.com/questions/890924/how-do-you-reload-a-django-model-module-using-the-interactive-interpreter-via-ma/3466579#3466579

Tomasz Zielinski
A: 

It seems that the general consensus on this topic, is that python reload() sucks and there is no good way to do this.

Mad Wombat