开发者

django, python: reload function in shell

I work in the django IPython-shell, which can be started with manage.py shell. When i load an extern function in the 开发者_JAVA百科shell for testing, everything is alright. But when i make changes to the function, the shell still has the old version of the function. Even if i make a new import.

Does anyone know how to reload the actual version of the function?

Thanks in regards!

Edit: I use windows - if that makes a difference.


I reload the module by remove it from the the sys.modules and make a new import.

import sys
sys.modules.pop('your.module')
import your.module
# or
from your.module import your_function


try using built in "reload" function on desired module.

http://docs.python.org/library/functions.html?highlight=reload#reload


Enable IPython autoreload extension before importing any code:

%load_ext autoreload
%autoreload 2

I use it with the regular django shell and it works perfectly, although it does have some limitations:

Caveats:

Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work:

  • Functions and classes imported via ‘from xxx import foo’ are upgraded to new versions when ‘xxx’ is reloaded.
  • Methods and properties of classes are upgraded on reload, so that calling ‘c.foo()’ on an object ‘c’ created before the reload causes the new code for ‘foo’ to be executed.

Some of the known remaining caveats are:

  • 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.*

source: https://ipython.org/ipython-doc/3/config/extensions/autoreload.html#caveats

Another great option is to write your code in a separate script and send it to django shell, like this:

manage.py shell < my_script.py


I wrote a script that works pretty well for reloading modules in IPython.

It is based on the technique in wrongite's answer above where you remove the module from sys.modules then reimport it.


The easiest solution I've found is combination of shell_plus and iPython which automatically reloads functions.

  1. pip install ipython
  2. pip install django-extensions
  3. add 'django_extensions' to your INSTALLED_APPS
  4. python manage.py shell_plus
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜