python / python/typing

Positional arguments to TypedDict constructor

未关闭
#2,161 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: typing spec
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

The spec says "The constructor takes only keyword arguments, corresponding to the items of the TypedDict." This derives from wording in PEP 589 "It can be used as a callable object with keyword arguments corresponding to the TypedDict items. Non-keyword arguments are not allowed."

But at runtime, the TypedDict constructor also takes positional arguments. This works:

from typing import TypedDict
class TD1(TypedDict):
    a: int
class TD2(TD1):
    b: str

def f(x: TD2) -> TD1:
    return TD1(x)

Pyright allows this program; mypy does not and reports Expected keyword arguments, {...}, or dict(...) in TypedDict constructor.

The spec should say whether or not this should be allowed. (My opinion: it should be allowed, since it works at runtime and doesn't appear to break any type safety rule.)

At runtime, even more is allowed; the TypedDict constructor actually allows whatever dict() allows. So you could do TD1([("a", 1)]), or TD1(TD2, a=3). Pyright allows some but not all of that. I'm inclined to prohibit anything other than calls with keyword arguments and calls with a single positional argument of TypedDict type; anything else is rarely useful and prone to unsound behavior.

贡献指南

这个仓库没有索引到贡献指南

从这里开始

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

调研方向

先从链接的 TypedDict 构造函数规范和 PEP 589 中对应的章节开始,然后将文档中的规则与这里描述的运行时示例以及 mypy 和 Pyright 的不同表现进行比较。确定允许的位置参数并使用清晰的规范性措辞更新规范后,即可视为完成。

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

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
冷清
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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