justinhj
justinhj

Reputation: 11316

Reloading a changed python file in emacs python shell

In the emacs Python shell (I'm running 2.* Python) I am importing a .py file I'm working with and testing the code. If I change the code however I'm not sure how to import it again.

From my reading so far it seems that

reload(modulename)

should work, but it doesn't seem to.

Perhaps just shutting down the python shell and restarting it would be enough, is there a command for that or you just do it manually?

edit: It looks like python-send-defun and python-send-buffer would be ideal, but changes don't seem to be propagating.

Upvotes: 7

Views: 7104

Answers (3)

Robin Tournemenne
Robin Tournemenne

Reputation: 104

After looking at this issue for quite an extensive amount of time, I came to the conclusion that the best solution to implement is, either based on an initialisation file of your python interpreter (ipython for exemple), or using the python build-in module "imp" and its function "reload". For instance at the beginning of your code:

import my_module
import imp
imp.reload(my_module)

#your code

This solution came to me from this page: https://emacs.stackexchange.com/questions/13476/how-to-force-a-python-shell-to-re-import-modules-when-running-a-buffer

Upvotes: 0

Roger Pate
Roger Pate

Reputation:

While reload() does work, it doesn't change references to classes, functions, and other objects, so it's easy to see an old version. A most consistent solution is to replace reload() with either exec (which means not using import in the first place) or restarting the interpreter entirely.

If you do want to continue to use reload, be very careful about how you reference things from that module, and always use the full name. E.g. import module and use module.name instead of from module import name. And, even being careful, you will still run into problems with old objects, which is one reason reload() isn't in 3.x.

Upvotes: 15

unutbu
unutbu

Reputation: 880977

It seems to work for me:

Make a file (in your PYTHONPATH) called test.py

def foo():
    print('bar')

Then in the emacs python shell (or better yet, the ipython shell), type

>>> import test
>>> test.foo()
bar

Now modify test.py:

def foo():
    print('baz')

>>> reload(test)
<module 'test' from '/home/unutbu/pybin/test.py'>
>>> test.foo()
baz

Upvotes: 5

Related Questions