python / python/mypy

Errors for union of callables could be better

Open
#15,048 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Given this definition (playground):

f: Callable[[int, int], None] | Callable[[int, str], None]

this code results in the following errors:

f(5, 42)  # E: Argument 2 has incompatible type "int"; expected "str"  [arg-type]
f(5, '42')  # E: Argument 2 has incompatible type "str"; expected "int"  [arg-type]

Looking at the errors (which are probably emitted in a for-loop) one would miss the big picture, which is that it's a union of two incompatible types.

Perhaps we could "meet" the callables, thus resulting in:

f(5, 42)  # E: Argument 2 has incompatible type "int"; expected <nothing>  [arg-type]
f(5, '42')  # E: Argument 2 has incompatible type "str"; expected <nothing>  [arg-type]

Notably we handle defaults well, i.e. in this code:

class FInt:
    def __call__(self, a: int, b: int=42) -> None:
        return

class FStr:
    def __call__(self, a: int, b: str='42') -> None:
        return

f: FInt | FStr

we get

f(5, 42)  # E: Argument 2 to "__call__" of "FStr" has incompatible type "int"; expected "str"  [arg-type]
f(5, '42')  # E: Argument 2 to "__call__" of "FInt" has incompatible type "str"; expected "int"  [arg-type]

but no error on

f(5)

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 with the two linked mypy playground examples and compare diagnostics for unions of callable types, including the default-argument case. Trace the callable argument-checking path that produces the reported errors. Done means diagnostics communicate that incompatible callable signatures cannot be met while preserving the valid default-argument behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.