user25854
user25854

Reputation: 13

NameError on list that's initialized in the constructor [Python3]

I'm extremely new to programming, and my projects thus far have consisted of Frankenstein-esque monsters of stitched together sample codes. This is my first project that I am developing largely independently. So far it has not gone well. It's fun though!

I'm working on a class function that returns only the values of one list that aren't in another given list. I found code from here, but I'm getting a NameError.

My code:

def __init__ (self, extracted): #Constructor
    allWords = extracted
    shelfFile = shelve.open('knownWordsPersistant') #Opens preexisting shelve module file
    knownWords = shelfFile['knownWords'] #The list that the error specifies

def getUnknownWords (self):
    return [x for x in allWords if x not in knownWords] #Line that causes error

And the error:

Traceback (most recent call last):
  File "C:\Users\Jack 
Hanson\Desktop\Programming\Python\VocabFinder\main.py", line 16, in <module>
    possUnknWrds = knownWordsObject.getUnknownWords(vocabArray)
  File "C:\Users\Jack 
Hanson\Desktop\Programming\Python\VocabFinder\KnownWordsUpdater.py", line 
16, in getUnknownWords
    if (inArray[i] not in knownWords):
NameError: name 'knownWords' is not defined

If you need any more context or information, I'll happily provide.

Upvotes: 1

Views: 187

Answers (1)

Pythonista
Pythonista

Reputation: 11635

This is a scoping issue....

You should set an attribute on the class self.knownWords and then use self.knownWords in your function. Same thing for allWords.

In your code you're attempting to reference local variables in getUnknownWords which aren't defined as the error message indicates.

Also, you shouldn't camel case things. Use underscores.

Upvotes: 2

Related Questions