Python global name not defined

I'm trying to test the following simple object:

class WebCorpus(object):
    def __init__(self):
        _index = {}
        _graph = {}
        _ranks = {}
        _corpusChanged = False

    def lookup(self, keyword):
        if keyword in _index:
            return _index[keyword]
        return None
# (some irrelevant code)

With:

from WebCorpus import WebCorpus

def test_engine():
    print "Testing..."
    content = """This is a sample <a href="http://www.example.com">webpage</a> with 
    <a href="http://www.go.to">two links</a> that lead nowhere special."""
    outlinks = ["http://www.example.com", "http://www.go.to"]

    corpus = WebCorpus()
    assert corpus.lookup("anything") == None
#(some more code)
test_engine()

But it gives me an error: NameError: global name '_index' is not defined. I don't understand this, _index is clearly defined in the __init__ !? What is my mistake here? Help appreciated.

Upvotes: 0

Views: 2261

Answers (2)

alecxe
alecxe

Reputation: 474161

In order to set class variables in the class method, you should use self:

class WebCorpus(object):
    def __init__(self):
        self._index = {}
        self._graph = {}
        self._ranks = {}
        self._corpusChanged = False

    def lookup(self, keyword):
        if keyword in self._index:
            return self._index[keyword]
        return None

Or, you can simplify the code and set variables like this (I've also simplified lookup method):

class WebCorpus(object):
    _index = {}
    _graph = {}
    _ranks = {}
    _corpusChanged = False

    def lookup(self, keyword):
        return self._index.get(keyword)

Note, the second example is not equivalent to the first one, because class-level variables are used, see comments below.

Upvotes: 4

mattr555
mattr555

Reputation: 27

What's happening here is that it's defining _index but then losing it after the __init__ is run. You should append self to everything, so it's self._index, etc. This goes for the entire class, not just in the __init__.

Upvotes: 2

Related Questions