Cannot turn existing dictionary into TypedDict

未关闭
#8,890 4 条评论 40 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
35/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
devtools

调研方向

首先使用 issue 中的 TypedDict 示例重现该诊断,并检查 mypy 的 TypedDict 构造函数检查。将被接受的字面量和 dict(...) 形式与被拒绝的现有字典形式进行比较;当预期支持的转换能够按照与运行时行为一致的方式进行类型检查,并由测试覆盖时,即表示完成。

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

描述

feature topic-typed-dict

I expected any of these forms to be allowed by MyPy, but they aren't:

# typed_dict_test.py
from typing import TypedDict

class D(TypedDict):
    a: str
    b: int


d_untyped = {"a": "foo", "b": 1}

d0 = D({"a": "foo", "b": 1})  # The only one that works
print(d0)

d1 = D(d_untyped)
print(d1)

d2 = D(**d_untyped)
print(d2)

d3 = D(dict(d_untyped))
print(d3)

d4 = D(dict(**d_untyped))
print(d4)
$ python typed_dict_test.py
{'a': 'foo', 'b': 1}
{'a': 'foo', 'b': 1}
{'a': 'foo', 'b': 1}
{'a': 'foo', 'b': 1}
{'a': 'foo', 'b': 1}
$ python -V
Python 3.8.3
$ mypy typed_dict_test.py 
typed_dict_test.py:13: error: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor  [misc]
    d1 = D(d_untyped)
         ^
typed_dict_test.py:16: error: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor  [misc]
    d2 = D(**d_untyped)
         ^
typed_dict_test.py:19: error: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor  [misc]
    d3 = D(dict(d_untyped))
         ^
typed_dict_test.py:22: error: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor  [misc]
    d4 = D(dict(**d_untyped))
         ^
Found 4 errors in 1 file (checked 1 source file)
$ cat mypy.ini 
[mypy]
warn_redundant_casts = True
warn_unused_configs = True
pretty = True
show_error_codes = True

disallow_any_generics = True
disallow_subclassing_any = True
disallow_untyped_calls = True
disallow_incomplete_defs = True
check_untyped_defs = True
disallow_untyped_decorators = True
no_implicit_optional = True
warn_unused_ignores = True
warn_return_any = True
no_implicit_reexport = True

I checked that cast(D, ...) works, but I wonder if this is the right way to proceed, or a workaround.

主要语言
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 摘要。