Skip to content Skip to sidebar Skip to footer

Reload Python Module

I am new to python and I have an issue with compiling the example code in Programming Collective Intelligence book which I am currently reading. I first make a file called recomme

Solution 1:

I think you have a conceptual problem here. recommendations.py is a file. From the way your code uses it, we can deduce that it defines a module - it is a module source file. You can load the module by writing import recommendations - you then have a module object in your session named recommendations. If you do that, then you can also reload the module using reload(recommendations). Note that reload will only work on a module object that has previously been imported from its module source file. It will not read the file for the first time and import the module. See the documentation for reload where it explains that.

In your case, you have not imported the module - you have imported a particular component of the module (critics) by using the line from recommendations import critics. Therefore, the interpreter session does not contain anything called recommendations and tells you so by giving the error you saw (NameError: 'recommendations' not defined).

My guess is that the book (I haven't got access to it), somewhere in the preceding code, has told you to type import recommendations. You must do this in the same interpreter session as where you type reload(recommendations) in order for the reload to work.

EDIT:

I have just noticed that the same question is posed here - it looks like there might be a problem in the book that it doesn't work if you just follow it through.

Solution 2:

The reload() works on modules (e.g. recommendations.py)

To reload recommendations, you can do like this:

import recommendations
# use recommendations.critics['name']

Then reload(recommendations)

The issue was that when you do from recommendations import critics, you've imported critics which was probably just a value inside your recommendations.py file, and not a module (not a critics.py file inside a recommendations folder). reload works on modules, doesn't work on objects inside a module

Post a Comment for "Reload Python Module"