I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well:
How do I unload (reload
ipython console does a deep reload with each reload()
expression; and of course adds a lot of other useful stuff.
I wasn't able to get any of the above solutions to work, but I did come up with a workaround for reloading any other non-models module in my django project (e.g. a functions.py
or views.py
module).
Create a file called reimport_module.py
. I stored it in the local/
folder of my django project on my dev machine.
# Desc: Imports the module with the name passed in, or imports it for first
# time if it hasn't already been imported.
#
# Purpose of this script is to speed up development of functions that
# are written in an external editor then tested in IPython.
#
# Without this script you have to exit & reenter IPython then redo
# import statements, definitions of local variables, etc.
#
# Note: doesn't work for Django models files, because Django caches
# them in a structure called AppCache.
#
# Args: module to reload (string)
import sys
module_to_reload = sys.argv[1]
# Attempt to pop module
try:
sys.modules.pop(module_to_reload)
print 'reimporting...'
except KeyError:
print 'importing for first time...'
# (re)import module
import_str = 'from {0} import *'.format(module_to_reload)
exec(import_str)
Launch shell plus (which uses an embedded IPython shell):
python manage.py shell_plus
Use the following to import the module you are developing:
%run local/reimport_module.py 'your.module'
Use IPython to test functions in your module.
Use the following to reimport the module without having to exit & reenter IPython:
%run local/reimport_module.py 'your.module'
Note: this command was already used in step 3, so you can type %run
then the up arrow to autocomplete it.
Assuming your project is set up this way
first load
from bookstore.shelf.models import Books
subsequent reloads
import bookstore;reload(bookstore.shelf.models);from bookstore.shelf.models import Books