r/learnpython • u/First-Ad6991 • 5d 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
View all comments
Show parent comment
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:
This is like if you had done:
Meaning, it assigns the name
queueas a global variable. The problem with your code is you havequeue = queue.Queue(maxsize=20000)inside the function. In Python, if you assign a name (likequeue) inside a function, the name is treated as a local variable within that function unless you use aglobalstatement to say otherwise.So before the code even runs,
queueis considered to be a local variable. That's a problem because before you assign anything to the local variablequeue, you havequeue.Queue(maxsize=20000). So, it seesqueue, and considers it to be a local variable for the reasons already mentioned. But, you haven't assigned anything toqueuelocally, so it throws the error you got.