python / python/mypy

Unpacking an iterable in a list comprehension leads to the type inferred as list[Any]

Open
#15,747 14 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug good-second-issue
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When a value of a user-defined class with __iter__ is converted into a list using [*value], the type of the list is inferred as list[Any].

To Reproduce

import typing

class Spam:
    def __iter__(self, /) -> typing.Iterator[int]:
        yield 1

a = Spam()

# list[int]
reveal_type(list(a))

# list[int]
reveal_type([i for i in a])

# list[int]
reveal_type([*(i for i in a)])

# list[int]
reveal_type([*a.__iter__()])

# list[Any] ???
reveal_type([*a])

b, = a
# int
reveal_type(b)

Expected Behavior

The type of [*a] is list[int]

Actual Behavior

example.py:22: note: Revealed type is "builtins.list[Any]"

Your Environment

  • Mypy version used: 1.4.1
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11.4

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 reproducer in the issue and trace how list displays handle starred expressions and iterable types. Add a regression test for a user-defined iter returning Iterator[int], then verify that [*a] is inferred as list[int] without breaking the other revealed types.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.