How to reload modules in django shell?

My solution to it is I write the code and save to a file and then use:

python manage.py shell < test.py

So I can make the change, save and run that command again till I fix whatever I'm trying to fix.


I'd suggest use IPython autoreload extension.

./manage.py shell

In [1]: %load_ext autoreload
In [2]: %autoreload 2

And from now all imported modules would be refreshed before evaluate.

In [3]: from x import print_something
In [4]: print_something()
Out[4]: 'Something'

 # Do changes in print_something method in x.py file.

In [5]: print_something()
Out[5]: 'Something else'

Works also if something was imported before %load_ext autoreload command.

./manage.py shell
In [1]: from x import print_something
In [2]: print_something()
Out[2]: 'Something'

 # Do changes in print_something method in x.py file.

In [3]: %load_ext autoreload
In [4]: %autoreload 2
In [5]: print_something()
Out[5]: 'Something else'

There is possible also prevent some imports from refreshing with %aimport command and 3 autoreload strategies:

%autoreload

  • Reload all modules (except those excluded by %aimport) automatically now.

%autoreload 0

  • Disable automatic reloading.

%autoreload 1

  • Reload all modules imported with %aimport every time before executing the Python code typed.

%autoreload 2

  • Reload all modules (except those excluded by %aimport) every time before executing the Python code typed.

%aimport

  • List modules which are to be automatically imported or not to be imported.

%aimport foo

  • Import module ‘foo’ and mark it to be autoreloaded for %autoreload 1

%aimport -foo

  • Mark module ‘foo’ to not be autoreloaded.

This generally works good for my use, but there are some cavetas:

  • Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only).
  • Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded.
  • C extension modules cannot be reloaded, and so cannot be autoreloaded.