Skip to content

Improve error messages for invalid shelve datum #137899

@picnixz

Description

@picnixz

Feature or enhancement

Proposal:

In #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

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions