Skip to content Skip to sidebar Skip to footer

Shelve Writes Blank Lists/dictionarys

I'm trying to make an API to create custom maps on a game I made, but shelve just writes blank lists and dictionarys. I try to store it like that: 'name' for the shown name of the

Solution 1:

shelve will write out changes to keys when you set that key. It can't detect changes to values. Appending to a list or assigning to a key on a dictionary that is value is going to go undetected.

From the shelve documentation:

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

Bold emphasis mine.

Either set the writeback parameter to True (and accept the downsides):

file1 = shelve.open("info", writeback=True)

or assign back to the key explicitly:

names = file1["name"]
names.append(name)
file1["name"] = names

Solution 2:

You need to open your file with writeback=True:

file1 = shelve.open("info",  writeback=True)

From the docs:

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

Post a Comment for "Shelve Writes Blank Lists/dictionarys"