2

This function is supposed to manipulate values in a dictionary stored as a file. I am getting

"local variable 'json' referenced before assignment"

on the fourth line, "dictio = json.loads()."

I have imported json, in fact the function below this runs perfectly well performing almost the same task. Unlike the later function, this one is also throwing an empty queue error, even though I have not intentionally asked for multithreading.

def updateTally(lefty):                                          #Tally records responses to each question
    global num, total, thisQ 
    rf = open("20QTally.json", "r")
    dictio = json.loads(rf.read())
    rf.close()

    dictio[str(0)] += 1
    total = dictio[str(0)]
    if lefty == 1:
        dictio[str(num)] +=1
    thisQ = dictio[str(num)]

    json = json.dumps(dictio)
    wf = open("20QTally.json", "w")
    wf.write(json)
    wf.close()

def record_score(score): # Opens, reads, writes, and closes the score file, 20QScores.txt (filename) global total scoref = open(filename, "r") # Records and reports individuals' responses sf = json.loads(scoref.read()) # Json helps with string and integer writing and reading to files. key = str(score) if key in sf: sf[key] += 1 else: sf[key] = 1 #etc.

2 Answers 2

5

you are trying to assign value to json here

json = json.dumps(dictio)

change the variable name

Sign up to request clarification or add additional context in comments.

2 Comments

Amazing! That is code I borrowed from somewhere. This change fixed both problems (I see now how the queue was being invoked now.) The error was coming on a different line, THANK YOU SO MUCH!
Just as an extra quirk - I was getting the same thing and was really confused since I wasn't declaring any variables named json, however; I think some sort of autocomplete or GitHub CoPilot or something like that had previously declared a variable named json and it was in a block of code that came after my return statement, and thus VS Code had it greyed out and my brain just completely ignored that it was there. So Python will still throw an error in code that is unreachable.
3

Its's because you are shadowing the json module declaring variable with the same name. Just don't do that, get some name that is unique within the scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.