Skip to content Skip to sidebar Skip to footer

Why Does Python's Shelve Require That All Keys Be Strings?

It's well-documented that Python's shelve module requires all keys to be strings and that there are various workarounds (see threads here and here). My question is, why does shelve

Solution 1:

Because under the hood the shelve module uses one of bsddb, gdbm or dbm for storage, and they support only string keys.

You're right that you can pickle a dict that uses other objects as keys, but then when one key changes, you have to flush the whole storage. By using a key-value database like those, only the changed values are flushed.

Solution 2:

May be somebody will find this example useful

classData:
    __slots__ = "name", "version"def__init__(self, name, version):
        self.name, self.version = name, version

    def__str__(self):
        return f"{self.name}:{self.version}"defencode(self, *args):
        s = self.__str__()
        return s.encode(*args)


def_d(s: str) -> Data:
    words = s.split(":")
    return Data(words[0], words[1]) 

import shelve
db = shelve.open("./db", flag="n", writeback=False)
print(Data("1", "2") in db)
for key indb:
    print(f"{_d(key)}")

Post a Comment for "Why Does Python's Shelve Require That All Keys Be Strings?"