raduw
raduw

Reputation: 1098

How to easily reload/reimport a module while working in a console

While working on a module I use the repl (python console) to test the functionality.

The problem I'm trying to solve is easily reloading the module and reimporting the module objects after a modification.

An example shows the problem.

In a console I start testing a function in package a.b.c

>>> from a.b.c import *
>>> myFunction(1)
wrong answer

I go back to the text editor and fix myFunction Now I want to re test it (I don't want to kill the repl and restart it, since I might have some test variables that I want to reuse)

So I have to do something like this:

>>> import a.b.c
>>> from importlib import reload
>>> reload(a.b.c)
>>> from a.b.c import *
>>> myFunction(1)
hopefully the right answer

I would like to write a function that would do the reload and reimport * in one go.

Ideally I would like to replace the previous session with something like

>>> myTestReload(a.b.c)
>>> myFunction(1)
hopefully the right answer

In the myTestReload() function I can use reload(a.b.c) to reload the modified module but I didn't find a way to do the equivalent of from a.b.c import *

Upvotes: 1

Views: 234

Answers (1)

Avezan
Avezan

Reputation: 671

This will reset globals here is an example with itertools.

import itertools
from itertools import *
from importlib import reload

itools = reload(itertools)

for k, v in itools.__dict__.items():
    if k in globals():
            globals()[k] = v

Upvotes: 2

Related Questions