r/learnpython • • 4d ago

i got UnboundLocalError: local variable 'queue' referenced before assignment, how to fix please

def main(ips, users, passwords, ThreadNumber):

queue = queue.Queue(maxsize=20000)

for t in range(ThreadNumber):

try:

t = Apophis(queue)

t.daemon = True

t.start()

except Exception as e:

break

2 Upvotes

6 comments sorted by

View all comments

Show parent comment

2

u/First-Ad6991 4d ago

it worked, thanks.

1

u/carcigenicate Carcigenicate 4d ago

Just to correct the original explanation so you understand why you got this error:

If you import a name, that doesn't make it a "reserved word". When you do this:

import queue

This is like if you had done:

queue = [Some import magic]

Meaning, it assigns the name queue as a global variable. The problem with your code is you have queue = queue.Queue(maxsize=20000) inside the function. In Python, if you assign a name (like queue) inside a function, the name is treated as a local variable within that function unless you use a global statement to say otherwise.

So before the code even runs, queue is considered to be a local variable. That's a problem because before you assign anything to the local variable queue, you have queue.Queue(maxsize=20000). So, it sees queue, and considers it to be a local variable for the reasons already mentioned. But, you haven't assigned anything to queue locally, so it throws the error you got.

1

u/supercoach 4d ago

Um, actually I said they should consider it a reserved word so that they don't use it. No assertion was made that it actually was a reserved word and no correction is needed.