python / python/mypy

Misleading issue text when return type doesn't match type annotation

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

Nobody has claimed this yet.

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

Description

Bug Report

When you return a function call like return list(...), return dict(...), and the type doesn't match the return annotation, the error message says that list(...) is not valid code.

To Reproduce

def foo() -> list[int]:
    tup = ("a", "b", "c")
    return list(tup)

Expected Behavior

I was expecting mypy to tell me that the type annotation doesn't match the return type.

Instead it says that the arguments to list() are wrong, i.e. list doesn't take this type.

Like so:

$ mypy asd.py
asd.py:3: error: Incompatible return value type (got "List[str]", expected "List[int]")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Actual Behavior

$ mypy asd.py 
asd.py:3: error: Argument 1 to "list" has incompatible type "Tuple[str, str, str]"; expected "Iterable[int]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

I think this is misleading.

Your Environment

  • Mypy version used: v1.0.1
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.10.9

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 diagnostic with the example in asd.py, using the reported mypy version and command. Trace how the return expression and its annotation are checked, then make the diagnostic identify the incompatible return value and add coverage for the list(...) and dict(...) cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.