Make42
Make42

Reputation: 13088

Re-import module "as"

I found quite a few answers regarding the question how to re-import a module (e.g. after I changed it during programming), but I want to re-import it as. In other words I would like to repeat

import main.mydir.mymodule as mymod

and have my changes incorporated into my console without restarting the console.

What I am trying currently when I try to reload is the following. I might run

import main.warp.optimisation as opt
res = opt.combiascend(par)

then I do some changes, for example I put a print('Yes, this worked.') at the end of the method combiascend, then I run

import importlib
import main
importlib.reload(main)
importlib.reload(main.warp.optimisation)
opt = main.warp.optimisation
res = opt.combiascend(par)

This does not work: I am not getting any error, but changes I did in the module optimisation just were not applied. In my example, I do not get the respective output.

Upvotes: 1

Views: 223

Answers (1)

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

After employing one of those other answers to "refresh" main.mydir.mymodule, simply do:

mymod = main.mydir.mymodule

Looks like importlib also updates the reference you give it, so if the original import used an alias, you can simply reimport the alias. Given empty foo/__init__.py and foo/bar/__init__.py, and a foo/bar/test.py containing this:

def func():
    print("a")

Then I get this:

>>> import foo.bar.test as mod
>>> mod.func()
a
>>> import importlib
>>> # (Updating the file now to print b instead)
>>> importlib.reload(mod)
<module 'foo.bar.test' from '/home/aasmund/foo/bar/test.py'>
>>> mod.func()
b

Upvotes: 2

Related Questions