Skip to content

Instantly share code, notes, and snippets.

@pawelztef
Created April 5, 2022 10:43
Show Gist options
  • Save pawelztef/ee8deca15c10d2c671ccd8d32247d3e6 to your computer and use it in GitHub Desktop.
Save pawelztef/ee8deca15c10d2c671ccd8d32247d3e6 to your computer and use it in GitHub Desktop.
how to reload modules in django shell
./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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment