python / python/cpython

Improve error messages for invalid `shelve` datum

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

还没有人认领这个 Issue。

extension-modules type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Feature or enhancement

Proposal:

In https://github.com/python/cpython/issues/137829, I got confused because of the following:

import shelve
import dbm.gnu

db = dbm.gnu.open("myshelf", "c")
db.close()

def serializer(obj, protocol=None):
    pass

def deserializer(data):
    return data.decode("utf-8")

with shelve.open("myshelf", serializer=serializer, deserializer=deserializer) as s:
    s["foo"] = "bar"

The traceback is

Traceback (most recent call last):
  File "/home/arf/Desktop/source-codes/cpython/repro.py", line 17, in <module>
    s["foo"] = "bar"
    ~^^^^^^^
  File "/home/arf/Desktop/source-codes/cpython/Lib/shelve.py", line 138, in __setitem__
    self.dict[key.encode(self.keyencoding)] = serialized_value
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: gdbm mappings have bytes or string indices only

I got confused because I thought that the issue stemmed from the key (because of the word "indices") but the error is raised due to the serialized_value type as serializer returns None. IOW, s["foo"] = "bar" above is equivalent to s["foo"] = None. I suggest:

  • changing the error message when the value type is incorrect (namely, don't talk about "indices"). Ideally, we should use "key" and "value" to distinguish the messages.
  • add some "must be [...], not [...]" with the input type.

cc @furkanonder

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs
  • gh-138768

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 Lib/shelve.py 的第 138 行开始,重现提供的 shelve/dbm.gnu 示例,以追踪为什么无效的序列化值会产生误导性错误。更新报告的措辞,以区分键和值,并包含接收到的类型;当示例能够清楚地指出无效值时,即视为完成。

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

评估

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

把新 issue 发到你的邮箱

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