Skip to content

Erroneous error about incompatible return value in generic function #14813

Closed as not planned
@OvervCW

Description

@OvervCW

Bug Report

Consider the following sample code:

from typing import TypeVar

T = TypeVar("T")


def identity(value: T) -> T:
    if isinstance(value, int):
        return value + 0
    else:
        return value


print(identity(2))
print(identity(True))

To Reproduce

Save this code to a file named test.py and run mypy test.py.

Expected Behavior

I would expect this code to pass with no errors since it always returns the same type as it was given.

Actual Behavior

Instead, mypy says this:

test.py:8: error: Incompatible return value type (got "int", expected "T")  [return-value]
Found 1 error in 1 file (checked 1 source file)

It seems that I can work around this problem by including an explicit cast:

from typing import cast

...

return cast(T, value + 0)

But I feel like that should not be necessary.

Your Environment

  • Mypy version used: mypy 1.0.1 (compiled: yes)
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: Python 3.11.1

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions