The Python Oracle

Python: Append to list owned by an instance stored in shelved dictionary

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC I Beethoven Sonata No 31 in A Flat M

--

Chapters
00:00 Question
02:15 Accepted answer (Score 1)
02:44 Answer 2 (Score 0)
03:18 Thank you

--

Full question
https://stackoverflow.com/questions/3014...

Accepted answer links:
[python docs]: https://docs.python.org/2/library/shelve...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #instances #shelve

#avk47



ACCEPTED ANSWER

Score 1


You need to extract, mutate and store the object back in the shelf to persist it.

e.g

# extract
this_friend = shelf[full_name]
# mutate
this_friend.add_timestamp(now)
# re-add
shelf[full_name] = this_friend
shelf.close()

You can see an example of this in the python docs.

The other option is pass the writeback parameter as True to shelve.open and it will allow you to write to the keys directly.




ANSWER 2

Score 0


@paulrooney answered this.

Objects in the shelf need to be removed from the shelf, assigned to a name, mutated (to add time stamp), then put back in the shelf. This code works fine.

shelf = shelve.open('/Users/Perrin/Library/Scripts/friend_shelf.db')

if full_name in shelf:
    this_friend = shelf[full_name]
    this_friend.add_timestamp(now)
    shelf[full_name] = this_friend
    print shelf[full_name].timestamps
    shelf.close

else:
    shelf[full_name] = Friend(full_name)
    this_friend = shelf[full_name]
    this_friend.add_timestamp(now)
    shelf[full_name] = this_friend
    shelf.close