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

Incorrect handling of unions of generics #14403

Open
hauntsaninja opened this issue Jan 6, 2023 · 1 comment
Open

Incorrect handling of unions of generics #14403

hauntsaninja opened this issue Jan 6, 2023 · 1 comment

Comments

@hauntsaninja
Copy link
Collaborator

This was originally reported in #3644 (comment)

from typing import Callable, TypeVar, Generic, Union

_U = TypeVar('_U')
_T = TypeVar('_T')

class Future(Generic[_T]):
    
    def __init__(self, t: _T):
        self._t = t

    def then(self, fn: Callable[[_T], Future[_U]]) -> Future[_U]:
        return fn(self._t)
    
    def then2(self, fn: Callable[[_T], _U]) -> Future[_U]:
        return Future(fn(self._t))
        
    def then3(self, fn: Union[Callable[[_T], Future[_U]], Callable[[_T], _U]]) -> Future[_U]:
        ret = fn(self._t)
        if isinstance(ret, Future):
            return ret
        else:
            return Future(ret)

def foo(t: int) -> Future[str]:
    return Future("str")

fut = Future(5)

reveal_type(fut.then(foo)) # is a Future[str], good

def foo2(t: int) -> str:
    return "str"
    
reveal_type(fut.then2(foo2)) # also is a Future[str], good

reveal_type(fut.then3(foo)) # <<==== error, Future[<nothing>]
reveal_type(fut.then3(foo2)) 
@eltoder
Copy link

eltoder commented Aug 23, 2023

I have a simpler example of the same issue: https://mypy-play.net/?mypy=latest&python=3.11&flags=strict&gist=d1a9097549000c37b75cd1bbba495b8a

from typing import Generic, TypeVar

T = TypeVar("T")

class C(Generic[T]):
    value: T

def unwrap(x: T | C[T]) -> T:
    return x.value if isinstance(x, C) else x

def test(x: C[int]) -> int:
    return unwrap(x)

produces

main.py:12: error: Argument 1 to "unwrap" has incompatible type "C[int]"; expected "C[<nothing>]"  [arg-type]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants