Incorrect handling of unions of generics
Open
Nobody has claimed this yet.
bug
topic-type-variables
topic-union-types
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
This was originally reported in https://github.com/python/mypy/issues/3644#issuecomment-825494986
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))
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied Python reproducer through mypy and checking the reveal_type results for then3. Trace inference for the Union of callable types, and consider the issue complete when both foo and foo2 are accepted and infer Future[str] rather than producing Future[nothing].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100