python / python/cpython

[docs] dictionary unpacking `fn(**kwargs)` should accept `SupportsKeysAndGetitem` and not just `Mapping`

未关闭
#157,747 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Brief

The docs say that for dict unpacking as in fn(**kwargs), kwargs must "implement the methods specified in the collections.abc.Mapping", when in reality only keys() and __getitem__ as in the dict constructor are required.

Documentation

The current documentation states that:

[6.2.5.4. Dictionary displays]
Instead of a key-value pair, a dict item may be an expression prefixed by a double asterisk **. This denotes dictionary unpacking. At runtime, the expression must evaluate to a mapping;

which points to

[mapping]
A container object that supports arbitrary key lookups and implements the methods specified in the collections.abc.Mapping or collections.abc.MutableMapping abstract base classes.

However, at runtime, fn(**kwargs) works whenever kwargs supports both a keys() -> Iterable[str] and __getitem__(self, key: str) -> object method:

class SupportsKeysAndGetitem:
    _dict = {"foo": 0, "bar": object()}

    def keys(self):
        return iter(self._dict)

    def __getitem__(self, key: str, /) -> object:
        return self._dict[key]

def expects_kwargs(**kwargs: int) -> None:
    print(kwargs)

d = SupportsKeysAndGetitem()
expects_kwargs(**d)  # works at runtime

Moreover, the relevant methods that Cpython executes under the hood explicitly supports this looser protocol:

class dict
If a positional argument is given and it defines a keys() method, a dictionary is created by calling getitem() on the argument with each returned key from the method.

and

int PyDict_Merge(PyObject *a, PyObject *b, int override)
Part of the Stable ABI. Thread safety: Safe for concurrent use on the same object.
Iterate over mapping object b adding key-value pairs to dictionary a. b may be a dictionary, or any object supporting PyMapping_Keys() and PyObject_GetItem().

Proposal

Update the documentation of dict-unpacking to reflect the actual runtime behavior in sync with how dict construction works, only requiring keys() and __getitem__ rather than inheritance from the non-protocol class collections.abc.Mapping.

Rationale

  • fn(**kwargs) only requiring keys() and __getitem__ is how it works at runtime, and has since ages
  • Supporting a protocol is nicer than just supporting a non-protocol ABC like collections.abc.Mapping due to duck-typing (a similar conclusion was reached in the discussion of #116938)
  • There are real world use-cases like fn(**dataframe) as for example a pandas DataFrame supports keys() (yields the list of columns) and __getitem__ (look up column by name), but does not inherit from the collections.abc.Mapping class, nor implements all of its methods.
Linked PRs
  • gh-157771

贡献指南

打开贡献指南

从这里开始

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

调研方向

结合 issue 中引用的 Dictionary 显示和 mapping 文档,审查关联的 PR gh-157771。根据所描述的 keys() 和 getitem 运行时行为核对措辞;完成的标准是文档不再要求继承 Mapping,并且仍与 dict 构造保持一致。

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

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
1/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 发到你的邮箱

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