Skip to content

Union is incorrectly constructed when callable() is used, resulting in a false positive #9778

Closed
@sirosen

Description

@sirosen

Bug Report

The following code fails type checking:

import typing

T = typing.TypeVar("T")

def callable_or_raise(foo: T) -> T:
    if foo and not callable(foo):
        raise ValueError("bad!")
    return foo

mypy reports foo.py:9: error: Incompatible return value type (got "Union[T, object]", expected "T")

Your Environment

  • Mypy version used: 0.790 and confirmed on master
  • Python version used: 3.6, 3.9

The oddest thing is that this will pass if I replace callable with a wrapper, e.g.

def check(x: object) -> bool:
    return callable(x)

reveal_type(check) is almost identical to reveal_type(callable):

foo.py:9: note: Revealed type is 'def (x: builtins.object) -> builtins.bool'
foo.py:10: note: Revealed type is 'def (builtins.object) -> builtins.bool'

This might be related to other false positives around Union + TypeVar (e.g. #6898) but I am unsure.

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