Search code examples
pythonunassigned-variable

Finding execution path leading to exception


My IDE is warning me against a possible variable reference before assignment. But I'm having trouble spotting it. I'm ready to turn in a bug report, but maybe you can see what I'm not seeing.

The variable in question is a named check_dialog and the reference before assignment warning happens at the end of the following code snippet in the line I marked for you:

    if dialog:
        validate = None
        string = False

        if dialog == Prompt.YES | Prompt.NO:
            check_dialog = lambda c: chr(c) in 'yn'
        elif dialog == Prompt.CONTINUE | Prompt.QUIT:
            check_dialog = lambda c: chr(c) in 'cq'
        elif dialog == Prompt.YES | Prompt.NO | Prompt.QUIT:
            check_dialog = lambda c: chr(c) in 'ynq'
        else:
            raise ValueError('Invalid dialog argument.')

    answer = None
    while not answer:
        self.addstr(0, 1, prompt)

        if string:
            curses.curs_set(True)
            curses.echo()
            answer = self.getstr(1, 3)
            curses.noecho()
            curses.curs_set(False)
        elif dialog:
            while not check_dialog(answer):  # warning here!
                answer = self.getch()
        else:
            answer = self.getch()

Solution

  • Your IDE is not "thinking" about every possible value of your variables (in most cases, this would be impossible) and instead is using heuristics to prevent common mistakes. In this case, it has noticed that check_dialog is defined within an if condition, but not in every case. Yet it is used below this condition. That might be an UnboundLocalError!

    As programmers, we can reason this out and see that the code paths it has noticed are protected. The else case raises a ValueError which will not be caught, and the usage is protected by (el)if dialog in both cases, so this will not be a problem.

    It is not a bug in your IDE, because it is doing what it is supposed to. If it really bothers you and you can't otherwise silence the warning, you can unnecessarily define something like check_dialog = None over the top of the first if dialog, and it will shut up. However, it is also not a bug with your program/code, which as reasoned above will not cause an UnboundLocalError. This is safe to ignore, and because of how your IDE probably works a bug report would just be closed.