python / python/mypy

Incorrect handling of unions of generics

Open
#14,403 1 comment 0 reactions 0 assignees View on GitHub

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.