shelve non-transparency

P

Paul Rubin

class x: pass
z = x()
z.a = 'a'

d = {'a': z}
for i in range(5):
print id(d['a'])

prints the same id 5 times as you'd expect.

d = shelve('filename')
d['a'] = z
for i in range(5):
print id(d['a'])

prints five different id's. So, for example,
y = d['a']
y.x = 'x'
fails to update the shelve.

The reason is sort of understandable but I hadn't guessed it ahead of
time (I'd actually forgotten that d wasn't a normal dict, which you're
supposed to be able to do if abstraction works properly), and it
caused a bug in my program that took a little while to figure out.

I wonder if some fix is possible.
 
M

Michele Simionato

The option writeback=True seems to work:

# put something in the shelve
import shelve

class C(object):
pass

s = shelve.open("x.shelve")
s["x"] = C()
s.close()

# read it
s = shelve.open("x.shelve", writeback=True)
c = s["x"]
c.attr = 1
print s["x"].attr # => 1
s.close()


Michele Simionato
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,314
Members
47,990
Latest member
MauricioEl

Latest Threads

Top