python / python/mypy

mypy is unable to correctly disambiguate a union when there is a dependent function type

Open
#14,421 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy is unable to correctly disambiguate a union when there is a dependent function type.
The call meow(s)(s) is always valid as s is either int or str and should not be able to take on both in the line.
However, the dependency of the return type of meow(s) on s is not remembered and mypy becomes upset.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=50bc3d85db8bc5120d881d37b891fd2a

from typing import overload, Callable, Union

@overload
def meow(a: int) -> Callable[[int], int]:
    ...

@overload
def meow(a: str) -> Callable[[str], str]:
    ...

def meow(a):
    return lambda x: x

# OK
a: str = 's'
meow(a)(a)

# Not ok though it should be
s: Union[int, str] = 's'
meow(s)(s)

Expected Behavior

Expected Behavior

Success: no issues found in 1 source file

Actual Behavior

main.py:20: error: Argument 1 has incompatible type "Union[int, str]"; expected "int"  [arg-type]
main.py:20: error: Argument 1 has incompatible type "Union[int, str]"; expected "str"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11

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 linked mypy-play example with Python 3.11 and mypy 0.991, then compare the accepted concrete-type call with the rejected Union call. Investigate how dependent return types from overloads are handled in this case. Done means the Union example produces “Success: no issues found in 1 source file” without the two arg-type errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.