Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incompatible return value type with TypeVar #10003

Open
marouane-miftah opened this issue Feb 1, 2021 · 4 comments
Open

Incompatible return value type with TypeVar #10003

marouane-miftah opened this issue Feb 1, 2021 · 4 comments
Labels
bug mypy got something wrong

Comments

@marouane-miftah
Copy link

marouane-miftah commented Feb 1, 2021

mypy=0.800
python=3.8.6

The following code generates
error: Incompatible return value type (got "str", expected "Union[ndarray, T]")

from __future__ import annotations
from typing import TypeVar, Union
import numpy

T = TypeVar("T")

def _test(a: list[T]) -> Union[numpy.ndarray, T]:
    if isinstance(a[0], str):
        return a[0]
    return numpy.array(a)
@marouane-miftah marouane-miftah added the bug mypy got something wrong label Feb 1, 2021
@giladreti
Copy link

giladreti commented Feb 1, 2021

Same here.

This code generates Incompatible return value type (got "int", expected "T"):

from __future__ import annotations

from typing import Type, TypeVar

T = TypeVar("T", bound=int)


def test(cls: Type[T]) -> T:
    if cls is int:
        return int()

    return cls()

@aucampia
Copy link

aucampia commented Jan 22, 2022

Also having this problem:

from typing import TypeVar
import unittest

AnyT = TypeVar("AnyT")


def strip_if_str(value: AnyT) -> AnyT:
    if isinstance(value, str):
        return value.strip()
    return value


class TestStripIfStr(unittest.TestCase):
    def test_str(self) -> None:
        self.assertEqual(strip_if_str(" a b c "), "a b c")

    def test_notstr(self) -> None:
        self.assertEqual(strip_if_str(3), 3)


if __name__ == "__main__":
    unittest.main()
$ python -m mypy --show-error-context --show-error-codes .
test_typevar_identity.py: note: In function "strip_if_str":
test_typevar_identity.py:9: error: Incompatible return value type (got "str", expected "AnyT")  [return-value]
Found 1 error in 1 file (checked 1 source file)
$ python -m unittest
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
$ python --version
Python 3.10.1
$ python -m mypy --version
mypy 0.931

I think this is similar to:

@fzimmermann89
Copy link

Are there any plans to fix this? Or is there a good work around?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

4 participants