python / python/mypy

iter(...) is not revealed the same as __iter__ method

Open
#21,027 0 comments 2 reactions 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

Bug Report

We are having issues with the pandas-stubs repo where the inference for __iter__ is different with iter(...).
With __iter__ we are seeing the right inference while with iter(...)

To Reproduce

from typing import Any, Generic, Never, TypeVar, reveal_type

_T_EXPANDING = TypeVar("_T_EXPANDING")
_T_STR = TypeVar("_T_STR", bound=Series)


class StringMethods(Generic[_T_EXPANDING, _T_STR]):
    def __getitem__(self, key: int) -> _T_STR: ...
    def __iter__(self) -> Never: ...

class Series:
    @property
    def str(self) -> StringMethods[Any, Series]: ...


def _0() -> None:
    reveal_type(StringMethods().__iter__())  # all 4 type checkers give Never

def _1() -> None:
    reveal_type(iter(Series().str))  # mypy: Any, pyright, pyrefly: Never, ty: Unknown

Expected Behavior

It is identifying it as Any.

Actual Behavior

We expect Never.

Your Environment

  • Mypy version used: mypy 1.19.1 (compiled: yes)
  • Mypy command-line flags: mypy test_file.py
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.14

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 by running the provided Python reproducer with mypy 1.19.1 and compare reveal_type(StringMethods().iter()) with reveal_type(iter(Series().str)). Trace the handling of the iter(...) expression relative to the iter method; done means mypy reports Never for the iter(...) case without changing the expected behavior elsewhere.

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
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.