Using python in an interactive mode one imports a module then if the module is changed (a bug fix or something) one can simply use the reload() command.
But what if I didn't import the entire module and used the 'from M import f,g' import statement. Is there any way to reimport only g?
(I tried removing the function from the parameter table by 'del g' AND delete the .pyc file from the directory. It didn't help. when I reimported the function 'from M import g' the old g was loaded).
You can't reload a method from a module but you can load the module again with a new name, say foo2 and say bar = foo2. bar to overwrite the current reference.
1 Answer. You can re-import a module in python, by using the importlib and its function reload.
When reload() is executed: Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module. The init function of extension modules is not called a second time.
Simple solution: Use the autoreload to make sure the latest version of the module is used. The autoreloading module is not enabled by default. So you have to load it as an extension. And each time you execute some code, IPython will reimport all the modules to make sure that you are using the latest possible versions.
When you do a from foo import bar
, you are importing the entire module. You are just making a copy of the symbol bar
in the current namespace. You are not importing just the function.
The reload
function is not totally reliable (e.g. it will not work for compiled C modules). I would recommend that you exit and restart your interpreter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With