itertools not defined when used inside module

Adam picture Adam · Dec 20, 2016 · Viewed 31.9k times · Source

I save my custom functions in a separate module that I can call when I need to. One of my new functions uses itertools, but I keep getting a name error.

NameError: name 'itertools' is not defined

It's really weird. I can import itertools in the console just fine, but when I call my function, I get a name error. Usually I can use functions from other libraries (pandas, sklearn, etc.) inside a custom function just fine as long as I import the library first.

BUT if I import itertools in the console, copy and paste my function into the console, and then call the function, it works fine.

It's making me crazy, but I'm thinking maybe I'm just not understanding the rules of modules or something.

here's the function i'm using in the module. it's simply copy and pasted from one of the sklearn examples:

import itertools    
def plot_confusion_matrix(cm, classes,
                              normalize=False,
                              title='Confusion matrix',
                              cmap=plt.cm.Blues):
        import itertools
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title(title)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes, rotation=45)
        plt.yticks(tick_marks, classes)

        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
            print("Normalized confusion matrix")
        else:
            print('Confusion matrix, without normalization')

        print(cm)

        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i, cm[i, j],
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")

        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label')

I tried importing it inside the function, inside the module, and inside the file where I am calling it - all with no luck. If I import it in the console its fine. Even after it's been imported in the console, if I run it inside the file I'm working on again, it gives the same error.

Answer

Adam picture Adam · Dec 21, 2016

It works now.

IMPORTANT LESSON: If you edit a module, you must close and reopen spyder/ipython/whatever. Simply resetting the kernel is not sufficient. Stupid of me, I know, but maybe maybe this answer will save someone time.