没有定义 name‘ reload’

我使用的是 python3.2.2。当我编写一个简单的程序时,我遇到了这个问题。

>>> reload(recommendations)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
reload(recommendations)
NameError: name 'reload' is not defined

我该怎么做?

112497 次浏览

You probably wanted importlib.reload().

from importlib import reload

In Python 2.x, this was a builtin, but in 3.x, it's in the importlib module.

Note that using reload() outside of the interpreter is generally unnecessary, what were you trying to do here?

An update to @Gareth Latty's answer. imp was depreciated in Python 3.4. Now you want importlib.reload().

from importlib import reload

Try importlib.reload.

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

from importlib import reload


reload(module_name)

As others have said, you need either importlib.reload(module) or at some earlier point you need to from importlib import reload. But you can hide the from importlib import reload in an initialization file. Make sure that PYTHONSTARTUP is defined in your shell. For example,

export PYTHONSTARTUP=$HOME/python/startup.py

might a reasonable line to add to your ~/.bash_profile, if your shell is bash, and depending on where you store your python files. (If you’re following these instructions, start a new terminal window at this point so that the line is executed.) Then you can put the line

from importlib import reload

in ~/python/startup.py and it will happen automatically. (Again, if you’re following along, start a new python session at this point.) This might look a bit complex just to solve this one problem, but it’s a thing you only have to do once, and then for every similar problem along the lines of “I wish python would always do this”, once you find the solution you can put it in ~/python/startup.py and forget about it.