Skip to content

False positive unreachable with redefined variable in loop #8865

Closed
@mthuurne

Description

@mthuurne

When checking the following code:

from typing import AbstractSet, Iterable, Optional, Set, TypeVar

T = TypeVar('T')

def intersection(seq: Iterable[AbstractSet[T]]) -> Optional[Set[T]]:
    ret = None
    for elem in seq:
        if ret is None:
            ret = set(elem)
        else:
            ret &= elem
    return ret

mypy reports:

$ mypy --warn-unreachable intersection.py
intersection.py:11: error: Statement is unreachable

This statement is the ret &= elem inside the else block.

It seems that mypy is using the initial type of ret to conclude that ret is None is always true, ignoring the fact that inside the loop ret is redefined to a different type.

If I place a reveal_type just before the return, mypy does report Union[builtins.set[T`-1], None] as the type, so it figures out the redefinition eventually.

I'm using mypy 0.770 on Pyton 3.8.2, with the --warn-unreachable flag.

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