Search code examples
pythonruntime-errorpraw

Fixing UnboundLocalError revolving around "local variable ' ' referenced before assignment."


I am trying to execute a translation with a module, though keep getting this error message relating to some of my variables:

UnboundLocalError: local variable 'usedWord' referenced before assignment

Here's my code for the reference:

def message_translate():
    for message in r.get_unread():
        message_text = message.body.lower()
        messageList = message_text.split()
        for word in message_text:
            if word in fullLangNames:
                usedWord = word
                index = fullLangNames.index(word)
                transLang = supportedLangs[index]
            elif word in abbrevLangNames:
                usedWord = word
                index = abbrevLangNames.index(word)
                transLang = supportedLangs[index]

        finalized_message_text = message_text.replace("/u/pleaseTranslate", "") and message_text.replace(usedWord, "")
        translation = (translator.translate(finalized_message_text, lang_from = 'en', lang_to = transLang))
        callback = (transMessage % translation)
        message.mark_as_read

Now I don't understand why I'm getting that error, or what the error is telling me. I apologize if this is an easy fix, though I've looked around and haven't found anything of significant use.

Thanks and I appreciate the help!


Solution

  • It looks to me that the problem is in the finalized_message_text. You should initialize usedWord = "" before the for loop. That should fix it. Or add the final Else statement to initialize usedWord = ""