Skip to content

Reachability check seems to consider isinstance(obj, Hashable) as always True #11799

Closed
@haxtibal

Description

@haxtibal

Running mypy --warn-unreachable (version 0.920) against the following snippet gives a false "unreachable statement" error.

from collections.abc import Hashable
from typing import List, Tuple, Union

def wrap_hash(obj: Union[Tuple[int], List[int]]):
    if isinstance(obj, Hashable):
        return hash(obj)
    return hash(id(obj))  # error: Statement is unreachable  [unreachable]

wrap_hash((0,)) # reaches 1st return
wrap_hash([0])  # reaches 2nd return

We can even exchange the Union annotation for a single unhashable type like List or Dict, and still get the same unreachable error. Looks like isinstance(obj, Hashable) is just considered True for any type.

Is this a mypy bug? Can we add some hints into the example code so that mypy would figure out correct reachability?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions