reimporting a single function in python
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?
(开发者_JS百科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).
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.
For from M import f, g
where M
is not an official python module, use:
import sys
import importlib
importlib.reload(sys.modules['M'])
then, reimport f
and g
using:
from M import f,g
If M
is an official python module, use
import importlib
importlib.reload(M)
from M import f,g
Since this is just for the interactive interpreter, I don't think that something like:
def my_reload(mod, name):
reload(mod)
globals()[name] = getattr(mod, name)
myreload(somemodule, "some_function")
would be terrible. This just reloads the module like normal and then rebinds the name pointing at the old object to the new object. This should work in all instances in which reload
would work to begin with. Alternatively, you could program it to take the actual object and get the name using its __name__
attribute. Functions, classes and modules all have a __name__
attribute but something like a module-level dictionary doesn't so it wouldn't be as flexible.
It will not replace references to the object that exist other than the global one but neither would reload
even if you originally accessed it with the dotted name. Once a reference to an object is loose, there's not much that you can do.
For the first import, bind the imported piece to a variable (which also speeds up look-up):
import numpy as NP
import numpy.linalg as LA
...
reload(LA)
精彩评论