tags:

views:

274

answers:

2

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.

+6  A: 

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.

Roger Pate
the important thing in this comment is that you not only have to re-load the module, but also to re-instantiate objects based on the 'new' module
Jehiah
Just fixing how you import won't make reload work in the general case. If you've stored anything from the imported module (eg. class instances), it won't be reloaded. To make reload work in general, you have to reload all of its users, recursively. Reload is brittle, and I strongly recommend against using it when testing--the last thing anyone needs when debugging is to be bit by a partial reload, leading to mysterious bugs that go away when you restart the shell.
Glenn Maynard
+1  A: 

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
unutbu
Thanks it works perfectly now, I must have been doing something weird.
justinhj