How to reload Python module in IDLE?
Asked Answered
I

4

14

I'm trying to understand how my workflow can work with Python and IDLE.

Suppose I write a function:

def hello():
    print 'hello!'

I save the file as greetings.py. Then in IDLE, I test the function:

>>> from greetings import *
>>> hello()
hello!

Then I alter the program, and want to try hello() again. So I reload:

>>> reload(greetings)
<module 'greetings' from '/path/to/file/greetings.py'>

Yet the change is not picked up. What am I doing wrong? How do I reload an altered module?

I've been reading a number of related questions on SO, but none of the answers have helped me.

Intermingle answered 4/6, 2011 at 2:56 Comment(1)
ctrl + f6 will restart your session as well.Undersigned
S
12

You need to redo this line:

>>> from greetings import *

after you do

>>> reload(greetings)

The reason just reloading the module doesn't work is because the * actually imported everything inside the module, so you have to reload those individually. If you did the following it would behave as you expect:

>>> import greetings
>>> greetings.hello()
hello!

Make change to file

>>> reload(greetings)
<module 'greetings' from 'greetings.py'>
>>> greetings.hello()
world!
Sommer answered 4/6, 2011 at 3:1 Comment(0)
P
5

Here's what I get when I try your example (from a fresh Python interactive session):

>>> from greetings import *
>>> reload(greetings)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'greetings' is not defined

This indicates the source of the problem. When you use from greetings import *, the name greetings is not imported into the global namespace. Therefore, you cannot use reload(greetings) on it.

To fix this, try the following:

>>> import greetings
>>> greetings.hello()
hello
>>> reload(greetings)
<module 'greetings' from 'greetings.pyc'>
>>> greetings.hello()
hello world
Prate answered 4/6, 2011 at 3:2 Comment(3)
I think in his example, he left out the fact that he did both import greetings and from greetings import *, so his example above works for him. In that case, reloading greetings alone would not cause a call to hello() to be updated, even though a call to greetings.hello() would work correctly.Sommer
@Sommer You are probably correct, I've tried a lot of things, and tried to distill the important behavior.Intermingle
@FarmBoy It's an error I've had happen to me before. I always get an "Oh, duh" feeling after I realize what's going on.Sommer
B
1

IDLE has a menu pick to run the current file. This will restart the shell by running your file first, reloading it.

Broody answered 4/6, 2011 at 2:59 Comment(1)
Or you could just hit f5 in the file editor (idle) or just use ctrl-f6. Tons easierGermayne
G
1

On windows, I use the shell->Restart shell or CTRL+F6 shortcut to restart and load the latest version of the modue

Grandfather answered 25/4, 2015 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.