reload a python module

Those days I was using ipython to perform some analysis and run some of my scripts. And in this time I needed to unload and reload some modules (some of mine and third-party ones). As it was said in the issue 9072, python does not support unloading modules and it seems it will not support (an error in my opinion; since we use ipython notebooks, to unload modules could be necessary).

But to reload a module it is allowed and supported!

We can start creating the file my_mod.py, having a function:

def fun_one ( arg1 ):
    return( arg1 + 2 )

Then we run ipython into the path and load the module:

In [1]: import my_mod
In [2]: my_mod.fun_one( 3 )
Out[2]: 5

So now, we change the content of my_mod and we let it as:

def fun_one ( arg1, arg2 = 2 ):
    return( arg1 + arg2 )

To reload the module and be able to use the new version of the function we should do:

In [3]: reload( my_mod )
Out[3]: <module 'my_mod' from 'my_mod.py'>
In [4]: my_mod.fun_one( 3, 5 )
Out[4]: 8
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: