Search code examples
pythonpython-3.xtensorflowkerasglobal-variables

Global Variable X is not defined error | Python Logic Error


I am trying to establish why this code does not work. I am following a tutorial but cannot for the life of me get this code to work as it does easily in the tutorial.

The error I am receiving is "Global Variable X is not defined".

When I debug the function it jumps straight over the global declaration. PyCharm also warns the declaration is not defined at the module level.

    def sentence_to_indices(sentence_words, word_to_index, max_len, i):
        global X, Y # Global variable 'X' & 'Y' is undefined at the module level
        sentence_indices = []
        for j, w in enumerate(sentence_words):
            try:
                index = word_to_index[w]
            except:
                UNKS.append(w)
                w = cleared(w)
                try:
                    index = word_to_index[w]
                except:
                    index = word_to_index['unk']
                    unks.append(w)
            X[i, j] = index

Here is where the function is being called

 try:
     for i, tk_lb in enumerate(cleaned_tokens_list):
            tokens, label = tk_lb
            sentence_to_indices(tokens, word_to_index, max_len, i)
            Y[i] = label
    except Exception as e:
        print(e)

Solution

  • The solution was actually to remove the Global declarations. As they weren't even required. I'll take some of the blame for being this stupid. Although I'll point the finger at the tutorial I was following.