Skip to content

(🐞) false narrowing with reassignment in loop #11612

Closed

Description

@KotlinIsland
a: int | None
a = None
for i in range(10):
    reveal_type(a)  # "None" and also "int | None"
    if a:
        print(a)  # error: unreachable
    a = i

Also:

a = None
for b in [1, 2]:
    if a is None:
        a = b
        continue
    print("hi")  # false unreachable error

Activity

  1. sobolevn commented on Dec 6, 2021

    @sobolevn
    Member

    This can be fixed by:

    a: int | None = None
    for b in [1, 2]:
        if a is None:
            a = b
            continue
        print("hi")  # ok

    The other question is: why a is not infered to be None | int?

  2. KotlinIsland commented on Dec 6, 2021

    @KotlinIsland
    ContributorAuthor

    It is, if you put reveal_type after the loop it reveals as int | None

    Perhaps it is inferring as int | None, but only past line 4, not considering the loop.

  3. changed the title [-]false unreachable with conditional reassignment then continue in loop[/-] [+](🐞) false unreachable with conditional reassignment then continue in loop[/+] on Oct 31, 2023
  4. changed the title [-](🐞) false unreachable with conditional reassignment then continue in loop[/-] [+](🐞) false unreachable with reassignment in loop[/+] on Oct 31, 2023
  5. KotlinIsland commented on Oct 31, 2023

    @KotlinIsland
    ContributorAuthor

    @sobolevn It's not just the inference, I've updated the OP with a much better example.

  6. changed the title [-](🐞) false unreachable with reassignment in loop[/-] [+](🐞) false narrowing with reassignment in loop[/+] on Oct 31, 2023
  7. added a commit that references this issue on Jan 9, 2025
    53d894a
  8. added a commit that references this issue on Jan 12, 2025
    9685171
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable codetopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions