python / python/mypy

False positive (and puzzling message) with union types and callables

Open
#13,720 0 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

To Reproduce

This works (no complains from mypy):

from typing import TypeVar, Callable

_T = TypeVar("_T")

class Param:
    def __init__(self, initialize: Callable[[], _T]) -> None:
        ...

Param(lambda: 1)

as well as:

from typing import TypeVar, Callable

_T = TypeVar("_T")

class Param:
    def __init__(self, initialize: _T | Callable[[], _T]) -> None:
        ...

Param(1)

but for this:

from typing import TypeVar, Callable

_T = TypeVar("_T")

class Param:
    def __init__(self, initialize: _T | Callable[[], _T]) -> None:
        ...

Param(lambda: 1)

mypy issues two weird messages:

src\playground.py:9: error: Argument 1 to "Param" has incompatible type "Callable[[], int]"; expected "Callable[[], <nothing>]"
src\playground.py:9: error: Return statement in function which does not return
Found 2 errors in 1 file (checked 1 source file)

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

Reproduce the three examples in src/playground.py and compare the diagnostics for the union involving Callable. Start by tracing mypy's handling of callable and union type inference, then add a regression test covering the failing example; done means the valid call produces no errors and the misleading return diagnostic is gone.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.