Skip to content

Incompatible return value type with TypeVar #10003

Closed

Description

@marouane-miftah

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)

Activity

  1. giladreti commented on Feb 1, 2021

    @giladreti

    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()
  2. aucampia commented on Jan 22, 2022

    @aucampia

    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:

  3. fzimmermann89 commented on Nov 10, 2024

    @fzimmermann89

    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

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