9

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.

2 Answers2

28

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • Thank you, it worked is there a book or something on the changes made in python 3.3.2? – Challee Cassandra Smith Aug 29 '13 at 00:18
  • @ChalleeCassandraSmith: As in between 3.3.1 and 3.3.2? Or 3.2 and 3.3? Or all the versions from 2.7 to 3.3? Whichever one you want, I don't know of any book, but the docs have an extensive [What's New in Python](http://docs.python.org/3.3/whatsnew/) section. – abarnert Aug 29 '13 at 00:22
  • @ChalleeCassandraSmith: But anyway, there isn't anything new here. Even in pre-1.0 versions of Python, you couldn't use functions from any module without importing that module, and the `imp` module has existed since Python 1.4. – abarnert Aug 29 '13 at 00:24
9

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.

Richie Bendall
  • 7,738
  • 4
  • 38
  • 58