r/learnpython • • 15h 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

0 Upvotes

4 comments sorted by

View all comments

1

u/supercoach 8h ago

I assume you're importing queue, so if you are, you need to consider it a reserved word and not use it for a variable name. Change the name of the var to anything else and you should be fine.

1

u/First-Ad6991 3h ago

it worked, thanks.

•

u/carcigenicate Carcigenicate 24m 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.