python / python/mypy

Misleading error message when incompatible return type and `iter`

Open
#15,408 0 comments 3 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

I was adding type hints to an __iter__ method which returns an Iterator from a tuple with different types. MRE is as follows:

def func(cls: type, **options: Any) -> Iterator[Union[type, Dict[str, Any]]]:
    as_tuple = (cls, options)
    return iter(as_tuple)

As you can see Iterator[Union[type, Dict[str, Any]]] is wrong with mypy because of how it handles unions vs joins (Iterator[object] works).

But the problem I had is the error message returned by this snippet:

error: Argument 1 to "iter" has incompatible type "tuple[type, dict[str, Any]]"; expected "SupportsIter[Iterator[type | dict[str, Any]]]"  [arg-type]

While when using:

def func(cls: type, **options: Any) -> Iterator[Union[type, Dict[str, Any]]]:
    as_tuple = (cls, options)
    rv = iter(as_tuple)
    return rv

We get a way better error message:

error: Incompatible return value type (got "Iterator[object]", expected "Iterator[type | dict[str, Any]]")  [return-value]

I don't know if this is specific to this iter use case, but never encountered it before.

  • Mypy version used: master
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files):
  • 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 with the two minimal reproductions in the issue and compare diagnostics for direct iter(as_tuple) versus assigning its result before returning. Trace the iter call's type-checking path and add a regression test covering the reported tuple and expected return annotation. Done when the direct form reports the useful incompatible-return-value context shown by the two-step form without regressing existing iter diagnostics.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.