Marco
Marco

Reputation: 1493

Python reload, and IPython autoreload as well, is not working

I am using Python + IPython for Data Science. I made a folder that contains all the modules I wrote, organised in packages, something like

python_workfolder
|
|---a
|   |---__init__.py
|   |---a1.py
|   |---a2.py
|
|---b
|   |---__init__.py
|   |---b1.py
|   |---b2.py
|
|---c
|   |---__init__.py
|   |---c1.py
|   |---c2.py
|
|
|---script1.py
|---script2.py

At the beginning of each session I ask IPython to autoreload modules:

%load_ext autoreload
%autoreload 2

Now... let's say a1.py contains a class, A1, that I want to call from one of the scripts. In the __init__.p of package a I import the module

import a1

Then in the script I import the class I need

from a.a1 import A1

If there is some error in class A1 and I modify it, there is no way to have Python reload it without restarting the kernel.

I tried with del a1, del sys.modules['a1'], del sys.modules['a']. Each time it uses the old version of the class until I don't restart the kernel... anyone can give me some suggestions?

Upvotes: 1

Views: 1657

Answers (2)

Mathador
Mathador

Reputation: 154

Old thread, but I had the same problem, so here is the solution I found. You have to use the module sys and before importing a1 write the following sys.modules.pop('a1'):

import sys

sys.modules.pop('a1')
import a1

The module is then reloaded.

Upvotes: 1

Marco
Marco

Reputation: 1493

This is funny. It seems that my problem is not due to IPython but to Pyzo (the IDE I'm using). I added a TestClass to a1:

class TestClass:
    def __init__(self):
        pass
    def disp(self):
        print('AAA')

This is the output I get from running the commands in an IPython shell:

In [2]: from a.a1 import TestClass
In [3]: t=TestClass()
In [4]: t.disp()
AAA

Now I modify disp to print 'BBB'

In [5]: t.disp()
BBB

So it was actually reloaded... also because if I skip running the autoreload commands at the beginning, it prints 'AAA' again. So it's working.

Instead if I run the commands through Pyzo (create a script, select the lines and press F9 or right click on the editor tab and select 'Run file') it doesn't get reloaded!

In [2]: (executing lines 1 to 3 of "testscript.py")
AAA

Again I modify disp to print 'BBB'

In [3]: (executing lines 1 to 3 of "testscript.py")
AAA

Upvotes: 0

Related Questions