Skip to content

mypy should error when code might raise UnboundLocalError #5714

@dgoldstein0

Description

@dgoldstein0
  • Are you reporting a bug, or opening a feature request?

Feature request

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

I found a case in my code recently where I had a typed function that had an UnboundLocalError - one of the branches used a variable that was undefined, but the same name was used in another place so mypy just assumed that it would be written before it was read. A simplified version would be like this:

def g(a,b):
  # type: (bool, bool) -> None
  if a:
    for m in [1,2]:
      pass
  if b:
    return m # bug here

Another related scenario (credit: @gvanrossum for this code):

def g(b):
    # type: (bool) -> None
    if b:
        x = 1
    y = x  # Here we don't actually know whether x exists

An even simpler case from @ilevkivskyi:

y = x
x = 1
  • What is the actual behavior/output?

Mypy doesn't give errors about this code

  • What is the behavior/output you expect?

I would like mypy to detect these as bugs. In particular it would probably make sense if there were a flag like --strict-optional for this - given that this behavior probably would break existing projects if it were on by default. I would like any variable that mypy can't prove is assigned before use to be an error; if mypy can't prove a variable is written before use, even if it is, I'd consider that poorly-written code. I suppose I just expect some basic control-flow analysis - once a variable is written, it's available to all lines in the same basic block, and any basic block that can only be reached by a basic block that assigns that local.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions