James Reid James Reid - 1 month ago 6
Python Question

local variable 'statement' referenced before assignment

I am currently creating a while loop in python and I got this problem:

local variable 'statement' referenced before assignment


this is my code:

while (statement == True):
self.headNode = settings.EMPTY_UUID
try:
lastNode = Task.objects.get(next = self.headNode)
self.headNode = lastNode.id
statement = True
except:
statement = False


I am worried if I initialize statement = True before while statement because it might become an infinite loop

For instance, this is data of Task.objects:

id name next
001 task1 002
002 task2 003
003 task3 000


I would like to get the Id of the root task which should be
001

Answer

The comments already point you to the answer, but here's a (more Pythonic) way to code this:

while True:
    self.headNode = settings.EMPTY_UUID
    try:
        lastNode = Task.objects.get(next=self.headNode)
        self.headNode = lastNode.id
        break
    except Task.DoesNotExist:
        break

Even if you'd need the value of statement after the while loop, you don't need the variable: statement is obviously False at that point.

Note that I've also changed the except statement. It's my assumption you want to catch the error that's raised when the relevant Task object does not exist, but it's generally bad to have a bare, catch-all, except.

Comments