python / python/mypy

List comprehension with TypedDict fails type checking

Open
#10,371 1 comment 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-typed-dict
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

I've made a file t.py:

from typing import TypedDict, List


class Dct(TypedDict):
    x: int


def foo() -> List[Dct]:
    return [item for item in [{"x": 3}]]

Expected Behavior

(Write what you thought would happen.)

Without the list comprehension, it works fine:

from typing import TypedDict, List


class Dct(TypedDict):
    x: int


def foo() -> List[Dct]:
    return [{"x": 3}]

Actual Behavior

$ mypy t.py
t.py:9: error: List comprehension has incompatible type List[Dict[str, int]]; expected List[Dct]  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 0.812
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.8.8
  • Operating system and version:

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 reproducing the report with the provided t.py example and mypy 0.812, comparing the list-comprehension result with the direct list return. Trace the type-checking path for list comprehensions and TypedDict values; done means the comprehension is accepted as List[Dct] without regressing related checks.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.