Mypy: False error in conditional expression returning union

Created on 24 May 2019  路  4Comments  路  Source: python/mypy

  • Are you reporting a bug, or opening a feature request?

Bug

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from typing import TypeVar, Union


T = TypeVar("T")


def get_or_str(value: T) -> Union[str, T]:
    return value


def f(b: bool) -> Union[str, bool]:
    return "" if b else get_or_str(True)
  • What is the actual behavior/output?

a.py:12: error: Argument 1 to "get_or_str" has incompatible type "bool"; expected "str"

  • What is the behavior/output you expect?

No error.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

0.710+dev.5f08ccf029aa3046b15e1afc60743ba692e4758d (from master)

  • What are the mypy flags you are using? (For example --strict-optional)

None

bug false-positive priority-1-normal topic-type-variables

All 4 comments

There is a similar error when trying to return a Sequence using tuples of different lengths:

def f(b: bool) -> Sequence[int]:
    return (1,) if b else (2, 3)

a.py:4: error: Incompatible return value type (got "object", expected "Sequence[int]")

The tuple example is a separate (relatively simple, but old) issue. The original example is just another case (among dozens) where single-bin inference would help.

I think we should really do this.

A similar problem:

from typing import Union

def f(a: Union[str, int], b: Union[str, int]) -> Union[str, float]:
    return a if isinstance(a, str) else b if isinstance(b, str) else a / b

a.py:4: error: Incompatible return value type (got "object", expected "Union[str, float]")

Likely the same issue:

from typing import Callable, Optional, TypeVar

T = TypeVar("T")

def f(
    a: Callable[[], T],
    b: Callable[[], T]
) -> T:
    return a()

op: Optional[int] = f(lambda: 1, lambda: None)

a.py:11: error: Incompatible return value type (got "None", expected "int")

Works bare T instead of callables.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

msullivan picture msullivan  路  26Comments

ilevkivskyi picture ilevkivskyi  路  25Comments

spkersten picture spkersten  路  40Comments

JukkaL picture JukkaL  路  28Comments

JukkaL picture JukkaL  路  47Comments