python / python/mypy

Misleading warning for generic argument type on wrong return type

Open
#12,156 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

It appears Mypy propagates types into the type arguments of a function call if the types on the left side are know, slightly obscuring the actual error.

To Reproduce

Run mypy a.py with

import typing as t

T = t.TypeVar('T')
U = t.TypeVar('U')

def coalesce(a: T | None, b: U) -> t.Union[T, U]:
  if a is None:
    return b
  return a

def foo() -> int:
  return coalesce(42, None)

Expected Behavior

Looking at this, I would expect Mypy to complain that the declared return value of foo() (being int) does not match what is actually returned (int | None).

Actual Behavior

It appears that Mypy propagates the return type into the coalesce() type arguments instead and expects them both to be int, thus complaining about the argument type instead.

a.py: note: In function "foo":
a.py:15: error: Argument 2 to "coalesce" has incompatible type "None"; expected "int"  [arg-type]
      return coalesce(42, None)
                          ^
Found 1 error in 1 file (checked 1 source file)

I find this rather unintuitive. My suggestion would be to make Mypy complain about the type of the returned value instead of the argument type.

Your Environment

  • Mypy version used: 0.931

  • Mypy command-line flags: /

  • Mypy configuration options from pyproject.toml (and other config files):

    [tool.mypy]
    pretty = true
    warn_redundant_casts = true
    #warn_unused_ignores = true
    warn_no_return = true
    warn_unreachable = true
    show_error_context = true
    show_error_codes = true
    
  • Python version used: 3.10.2

  • Operating system and version: WSL 2, Ubuntu 20

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 supplied a.py reproducer and run mypy a.py using the reported configuration and Python version. Compare the current argument-type diagnostic with the requested return-type diagnostic, and use that difference to identify the type-inference behavior that needs investigation. Done means the example reports the return mismatch rather than rejecting None as an argument.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.