Why I get the 'NameError: free variable '???' referenced before assignment in enclosing scope'?

Viewed 328

I was writing a simple python code the other day using 3D-Slicer (v4.11) and Python (v3.6.7) on Windows 10.

Source code below:

def RunCLI(self, module, params, onCompletedHandler):
    cliNode = slicer.cli.run(module, None, params)

    mask = cliNode.Cancelled | cliNode.Completed

    completed = False

    def OnStatusModified(caller, event):
        nonlocal completed

        if completed: return # Error

        status = cliNode.GetStatus() # Gives the same error for 'cliNode' if I comment the previuos line

        if status & mask != 0:
            completed = True
            onCompletedHandler()

    cliNode.AddObserver('ModifiedEvent', OnStatusModified)
    OnStatusModified(None, None)

It occasionally gives me the error:

'NameError: free variable 'completed' referenced before assignment in enclosing scope'.

I have no clue why it happens and why sometimes it passes and sometimes it fails.

I'm not sure what is the internal implementation of cliNode (I don't think it matters) but I guess cliNode runs an executable in another thread and signals the status changes through 'ModifiedEvent'.

Appreciate your help.

0 Answers
Related