Duplicate keys cause earlier TypedDict values to be skipped during type checking

未关闭
#21,841 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
74/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
冷清
技术栈
python
领域
compilers

调研方向

从 mypy/checkexpr.py 第 839-842 行附近开始,使用提供的 mypy 命令通过 example.py 重现该问题。跟踪重复的 TypedDict 键如何替换之前的表达式;完成标准是每个值表达式都经过类型检查,并且 parse(123) 这一情况报告预期的 arg-type 错误。

由索引模型根据 Issue 内容生成。

描述

bug topic-typed-dict

Bug Report

When a dictionary literal used to construct a TypedDict contains duplicate
keys, mypy only type-checks the final value for that key. Earlier value
expressions are skipped entirely.

This can hide real errors because Python still evaluates every value expression
in the dictionary literal, including values that are later overwritten by a
duplicate key.

To Reproduce

from typing import TypedDict


class Payload(TypedDict):
    value: int


def parse(value: str) -> int:
    return len(value)


payload = Payload({"value": parse(123), "value": 0})
$ mypy --show-error-codes --no-incremental example.py
Success: no issues found in 1 source file

Running the program demonstrates that the skipped expression is evaluated:

TypeError: object of type 'int' has no len()

Expected Behavior

Mypy should type-check every value expression in the dictionary literal, even
if a later duplicate key determines the final value of the TypedDict field.
In this example, it should report an error similar to:

error: Argument 1 to "parse" has incompatible type "int"; expected "str"  [arg-type]

The same expression is correctly rejected when the target is a regular
dict[str, int]. The issue also occurs with a contextually typed literal:

payload: Payload = {"value": parse(123), "value": 0}

Actual Behavior

Mypy reports no issues because only the last value associated with the
duplicate key is checked.

Additional Context

The current implementation replaces the previously collected expression
without type-checking it and has a TODO to type-check all duplicate-key values:

https://github.com/python/mypy/blob/6eb141f03a8b43c274f15cc4978d617a71d8f37e/mypy/checkexpr.py#L839-L842

PR #15425 also mentioned repeated TypedDict keys as a known limitation, but I
could not find an existing issue that tracks it:

https://github.com/python/mypy/pull/15425

Environment Used to Reproduce

  • Mypy versions used:
    • mypy 2.3.0 (compiled: yes)
    • mypy 2.4.0+dev.6eb141f03a8b43c274f15cc4978d617a71d8f37e (compiled: no)
  • Mypy command-line flags: --show-error-codes --no-incremental
  • Mypy configuration options: none
  • Python version used: 3.12.8
主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 18 小时
30 天内合并 PR
54

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。