python / python/mypy

def typed with Union passed twice is wrongly reported "Incompatible return value type"

Open
#10,225 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

mypy errantly cites error got "Tuple[Optional[str], Optional[str]]", expected "Union[Tuple[str, str], Tuple[None, None]]". Seems to mix up the Union and Optional.


First, given file test1.py that passes mypy

from typing import Union, Tuple

def def1(var: bool) -> Union[Tuple[str, str], Tuple[None, None]]:
    a, b = "", ""
    if var:
        return a, b
    return None, None

Run command

python -m mypy test1.py

(test1.py passes).

Then add a call to another function with the same type declaration.

Given file test2.py

from typing import Union, Tuple

def def1(var: bool) -> Union[Tuple[str, str], Tuple[None, None]]:
    if var:
       return "", ""
    return None, None

def def2(var: bool) -> Union[Tuple[str, str], Tuple[None, None]]:
    a, b = def1(var)
    if var:
        return a, b
    return None, None

The same mypy command fails test2.py

python -m mypy test2.py
test2.py:8: error: Incompatible return value type (got "Tuple[Optional[str], Optional[str]]", expected "Union[Tuple[str, str], Tuple[None, None]]")
Found 1 error in 1 file (checked 1 source file)

Environment

  • Mypy version used: mypy 0.812
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8.5
  • Operating system and version: Windows 10 Pro

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Run python -m mypy test2.py and compare it with test1.py, focusing on the type-checking path for unpacking the Union[Tuple[str, str], Tuple[None, None]] result in def2. Done means test2.py no longer reports the incorrect incompatible-return-value error while test1.py remains passing.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.