Skip to content

Incompatible return type with Union when not all Union variants are possible #12737

@barollet

Description

@barollet

Bug Report

I have a common interface with two backends and not all backends can return every variant of some unions that are returned. I tested on a really small example to demonstrate the issue and it seems like the error is still here.

To Reproduce

Here is the small exemple (in the project the types are not primitive types but anyway).

def f() -> dict[int, int | str] | int:
    a = {1: "hello"}
    return a

print(f())

In a file test_mypy.py

I have to specify the whole union because the interface is common and maybe the other backend implementation of function f will return either an int or a dict[int, int].

Expected Behavior

If I run mypy on this program I would expect it to typecheck a is a dict[int, str], we expect the return value to be of type either int or dict[int, str | int].
This is not an int, so this has to be of type dict[int, str | int], the key is of correct type and the value str is in str | int.

Maybe I misunderstood the Union syntax or meaning

Actual Behavior

When I run mypy test_mypy.py I obtain

test_mypy.py:3: error: Incompatible return value type (got "Dict[int, str]", expected "Union[Dict[int, Union[int, str]], int]")
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.942
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files): Default one for this test
  • Python version used: 3.10
  • Operating system and version: 4.19-Manjaro

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions