views:

37

answers:

1

Hello. For this example, I have a dictionary, that when I call on it, "Ember Attack" is displayed.

#import shelve
class Pokemon():
"""Each pokemon's attributes"""

def __init__(self):
    self.id=[]
    self.var1=[]
    self.var2=[]
    self.var3=[]
    self.var4=[]
    self.var5=[]

def __str__(self):
     showList=['id','var1', 'var2', 'var3', 'var4', 'var5']

#dict1=shelve.open("shelve.dat")
dict1={}
dict1["Charmander"]=Pokemon()
dict1["Charmander"].var1="Ember Attack"
#dict1.sync()
print dict1["Charmander"].var1
#dict1.close()

However when I start using shelves instead of the dictionary, I get a blank when I call on var1.

import shelve

class Pokemon():
"""Each patient's attributes"""

def __init__(self):
    self.id=[]
    self.var1=[]
    self.var2=[]
    self.var3=[]
    self.var4=[]
    self.var5=[]

def __str__(self):
    showList=['id','var1', 'var2', 'var3', 'var4', 'var5']

dict1=shelve.open("shelve.dat")
#dict1={}

dict1["Charmander"]=Pokemon()
dict1["Charmander"].var1="Ember Attack"

dict1.sync()

print dict1["Charmander"].var1

dict1.close()

The only difference is that I made dict1 a shelve dictionary instead of a regular dictionary. It probably has to do with memory scope or something. Anyway, can someone help me revise my code so that it will work with shelves? Thanks!

+1  A: 
dict1=shelve.open("shelve.dat", writeback=True)

you can also specify the protocol which should improve performance

dict1=shelve.open("shelve.dat", protocol=2, writeback=True)

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).

gnibbler
Your second line of code works!!!! THANK YOU SO MUCH!!!!!!!!!
Brian