recursive reload() "from some_module import *" in python
python, python-import, spyder
Solution
A very heavy handed solution, so to speak, is to save the state of `sys.modules` before you import the module chain, then restore it to its original state before importing the modules again.
import sys
bak_modules = sys.modules.copy()
import KosmoSuite as ks
# do stuff with ks
# edit KosmoSuite
for k in sys.modules.keys():
if not k in bak_modules:
del sys.modules[k]
import KosmoSuite as ks
However, there are some caveats:
- You may need to reimport even unrelated modules that you've imported in the meanwhile.
- If you have created any objects using the old version of the module, they retain their old classes.
Still, I've used it when developing a module while testing it in an interactive session, and if you take the limitations into account, for the most part it works fine.
Problem
I have module called `KosmoSuite` initialized by folowing `__init__.py` ``` ... from chemical_fuels import * from orbital_mechanics import * from termodynamics import * from rail_guns import * ... ``` in files `chemical_fuels.py, orbital_mechanics.py, termodynamics.py, rail_guns.py` are some data tables, constants, and functions to conduct some physical computations (for example function `orbital_mechanics.escape_velocity(M,R)` to compute escape velocity from a planet of given mass and radius) I would like to use python interpreter as interactive calculator of space-related problems. However, The problem is interactive developlopment and debugging. When I do ``` >>> import KosmoSuite as ks # ... modify something in orbital_mechanics.escape_velocity( ) ... >>> reload(ks) >>> ks.orbital_velocity( R, M) ``` However the `ks.orbital_velocity( R, M)` is not affected by my modifications to `orbital_mechanics.escape_velocity()`. Is there some alternative to `reload(ks)` which does the job ( i.e. reloading of all object, constants and functions imported by `from some_module import *` recursively ) Even better would be something like ``` >>> from KosmoSuite import * # ... modify something in orbital_mechanics.escape_velocity( ) ... >>> from KosmoSuite reimport * >>> orbital_velocity( R, M) ``` footnote : I'm using Spyder ( Python(x,y) ) right now, but the same is true for default python interpreter. In this question is something about deep-reload ( dreload ) in IPython. I'm not sure if it does exactly this job, but I don't like IPython anyway.