python / python/mypy

type inference failure on custom iterable class unpacking

Open
#20,435 2 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

When unpacking a custom iterable class to build another iterable, mypy does not correctly infer the resulting type i.e. CustomIter[CustomIter[_T]] is equal to CustomIter[_T] (that should not be true)

To Reproduce

proof-of-concept

Expected Behavior

Nested iterable unpacking type checking works fine when using standard types (e.g. list[list[_T]]) however custom iterable classes should have the same behavior.

Actual Behavior

As presented on the playground proof-of-concept the issue is that mypy does not mark the failure on this incorrectly defined function:

def case_1(iter_of_iter: CustomIter[list[int]]) -> CustomIter[int]:
    # Mypy fails
    #
    # Mypy does not flag that the return type does not match.
    # It is `CustomIter[list[int]]` instead of `CustomIter[int]`
    return CustomIter.new(*iter_of_iter)

Your Environment

  • details available on the playground example.

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 linked mypy-play proof of concept and reproduce the failure under its stated strict flags. Trace how unpacking a CustomIter[CustomIter[_T]] is inferred, then verify that the incorrect case is rejected while nested standard iterables retain their existing behavior.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.