Skip to content

Mypy error with tuple types Including TypedDict in return #16585

Open
@tomoris

Description

@tomoris

Bug Report

When using multiple tuple types, one of which includes TypedDict as a return value type, mypy generates errors.

from typing import TypedDict

class MyTypedDict1(TypedDict):
    a: int

class MyTypedDict2(TypedDict):
    b: int

def success_func1(x: int) -> MyTypedDict1:
    return {"a": x}

def success_func2(x: int) -> tuple[MyTypedDict1, int]:
    return {"a": x}, 1

def success_func3(x: int) -> MyTypedDict1 | MyTypedDict2:
    if x > 0:
        return {"a": x}
    return {"b": x}

def success_func4(x: int) -> tuple[int, float] | tuple[str, float]:
    if x > 0:
        return 1, 1.0
    return "1", 1.0

def success_func5(x: int) -> tuple[int, MyTypedDict1] | str:
    if x > 0:
        return 1, {"a": 1}
    return "1"

def success_func6(x: int) -> tuple[int, MyTypedDict1] | tuple[str]:
    if x > 0:
        return 1, {"a": 1}
    return ("1",)

def success_func7(x: int) -> tuple[int, dict[str, int]] | tuple[str, int]:
    if x > 0:
        return 1, {"a": 1}
    return "1", 1

def success_func8(x: int) -> tuple[int | str, MyTypedDict1 | MyTypedDict2]:
    if x > 0:
        return 1, {"a": x}
    return "1", {"b": x}

def mypy_err_func1(x: int) -> tuple[int, MyTypedDict1] | tuple[str, float]:
    if x > 0:
        return 1, {"a": 1}
    return "1", 1.0

def mypy_err_func2(x: int) -> tuple[int, MyTypedDict1] | tuple[str, MyTypedDict2]:
    if x > 0:
        return 1, {"a": x}
    return "1", {"b": x}

print(success_func1(1))
print(success_func2(1))
print(success_func3(1))
print(success_func4(1))
print(success_func5(1))
print(success_func6(1))
print(success_func7(1))
print(success_func8(1))
print(mypy_err_func1(1))
print(mypy_err_func2(1))

https://mypy-play.net/?mypy=master&python=3.11&gist=420e018ad82fe72420a40e4b05eb1275

Expected Behavior

$mypy tmp.py
Success: no issues found in 1 source file

Actual Behavior

$mypy tmp.py
tmp.py:47: error: Incompatible return value type (got "tuple[int, dict[str, int]]", expected "tuple[int, MyTypedDict1] | tuple[str, float]")  [return-value]
tmp.py:52: error: Incompatible return value type (got "tuple[int, dict[str, int]]", expected "tuple[int, MyTypedDict1] | tuple[str, MyTypedDict2]")  [return-value]
tmp.py:53: error: Incompatible return value type (got "tuple[str, dict[str, int]]", expected "tuple[int, MyTypedDict1] | tuple[str, MyTypedDict2]")  [return-value]
Found 3 errors in 1 file (checked 1 source file)

Your Environment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions