Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you reload a module in python version 3.3.2

Tags:

python

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.

like image 630
Challee Cassandra Smith Avatar asked Aug 29 '13 00:08

Challee Cassandra Smith


People also ask

How do I reload a Python module?

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.

How do I reload Python 3?

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).

What is Importlib 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.


2 Answers

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.

like image 172
abarnert Avatar answered Oct 02 '22 16:10

abarnert


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.

like image 41
Richie Bendall Avatar answered Oct 02 '22 15:10

Richie Bendall