Skip to content

unbound-name not reported after a for loop that contains break #5566

Description

@antoinespiers-pyl

If a variable is only assigned inside a for loop, pyrefly correctly warns when it's used after the loop. But as soon as the loop body contains a break, the warning goes away, even though the variable is still unbound when the iterable is empty.

def last_value(values: list[int]) -> int:
    for value in values:
        last = value
    return last  # UnboundLocalError when `values` is empty


def last_before_zero(values: list[int]) -> int:
    for value in values:
        last = value
        if last == 0:
            break
    return last  # UnboundLocalError when `values` is empty


last_before_zero([])

pyrefly check --preset default --python-version 3.14 loop_break.py with pyrefly 1.4.1:

ERROR `last` may be uninitialized [unbound-name]
 --> loop_break.py:4:12
  |
4 |     return last  # UnboundLocalError when `values` is empty
  |            ^^^^

Only line 4 is flagged. I'd expect line 12 as well, since running the file fails there:

UnboundLocalError: cannot access local variable 'last' where it is not associated with a value

For what it's worth, pyright 1.1.414 reports both lines (reportPossiblyUnboundVariable).

Activity

  1. added theissue type on Nov 7, 2026
  2. 1-DARK commented on Nov 7, 2026

    @1-DARK
    Contributor

    #claim

  3. github-actions commented on Nov 7, 2026

    @github-actions

    @1-DARK you've claimed this issue — it's now assigned to you. Thanks for picking it up! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

scoping-control-flowissues related to scoping and control flow

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions