whenever I try to reload a python module in python version 3.3.2 i get this error code
>>> import bigmeesh
>>> bob=bigmeesh.testmod()
this baby is happy
>>> imp.reload(bigmeesh)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
imp.reload(bigmeesh)
NameError: name 'imp' is not defined
I tried researching and still got no answers.
The reload() - reloads a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have mades changes to the code.
In Python 3, reload was moved from builtins to imp. So to use reload in Python 3, you'd have to write imp. reload(moduleName) and not just reload(moduleName).
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.
You have to import imp
before you can use it, just as with any other module:
>>> import bigmeesh
>>> import imp
>>> imp.reload(bigmeesh)
Note that the documentation clearly says:
Note: New programs should use
importlib
rather than this module.
However, in 3.3, importlib
doesn't have a simple reload
function; you'd have to build it yourself out of importlib.machinery
. So, for 3.3, stick with imp
. But in 3.4 and later which do have importlib.reload
, use that instead.
It's also worth noting that reload
is often not what you want. For example, if you were expecting bob
to change into an instance of the new version of bigmeesh.testmod()
, it won't. But, on the other hand, if you were expecting it to not change at all, you might be surprised, because some of its behavior might depend on globals that were changed.
This is the modern way of reloading a module:
# Reload A Module
def modulereload(modulename):
import importlib
importlib.reload(modulename)
Just type modulereload(MODULE_NAME)
, replacing MODULE_NAME
with the name of the module you want to reload.
For example, modulereload(math)
will reload the math function.
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