Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload Python module in IDLE?

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.

like image 288
Eric Wilson Avatar asked Jun 04 '11 02:06

Eric Wilson


People also ask

How do you reload a Python module?

The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.

How do I load a Python file in IDLE?

To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run → Run Module from the menu bar. Either option will restart the Python interpreter and then run the code that you've written with a fresh interpreter.

What is Importlib reload?

When reload() is executed: Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module.


1 Answers

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!
like image 99
Jacinda Avatar answered Oct 08 '22 01:10

Jacinda