gnikol
gnikol

Reputation: 227

Do I have to reload a module in python to capture changes?

I am running python 3.6.4 (anaconda, spyder).

Do I need to reload a user-defined module in order to capture the changes?

For example, suppose I wrote the simple function and save it in test.py file:

def plus5(x):
    return x + 5

Then in the IPython console I type

import test as t

and then I change the user-defined function to:

def plus5(x):
    return x + 500

Then when I type in IPython console

t.plus5(0)

it returns 500 without re-importing or reloading the module first.

If I change the function name from plus5 to something else then I have to re-import the module to see the change. But when I change the function statements then it automatically captures the changes without re-importing the module

From the Python documentation:

Note: For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload()

e.g. import importlib; importlib.reload(modulename).

Upvotes: 3

Views: 1286

Answers (2)

MegaIng
MegaIng

Reputation: 7886

This is a feature in the IPython interpreter name autoreload. It has the magic command %autoreload which allows for activating or deactivating this feature. It seems to be on by default, but I was not able to find something proving that.

Upvotes: 2

Saeed
Saeed

Reputation: 152

As Megalng explained, this is a built in feature of IPython interpreter and in default Python interpreter you have to use importlib to reload the module. Here is default python interpreter execution,

Python 3.6.2 (default, Sep  5 2017, 17:37:49) 
[GCC 4.6.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> 
>>> 
>>> import test as t
>>> t.plus5(0)
5
>>>   
>>> 
>>> #Changed function body to return x + 500    
... 
>>> t.plus5(0)
5
>>> import test as t
>>> t.plus5(0)   
5
>>> #It had no affect, even importing again doesn't work.
... 
>>> import importlib; importlib.reload(t)         
<module 'test' from '~/test.py'>
>>> 
>>> t.plus5(0)
500
>>> #Now it works !
... 
>>> 

As you can see, even after changing function body to return x + 500, it still generated a result of 5 for t.plus5(0), even importing test module again did not help. It only started working when importlib was used to reload test module.

Upvotes: 1

Related Questions