shelve non-transparency

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Rubin

    #1

    shelve non-transparency

    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('filenam e')
    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.
  • Michele Simionato

    #2
    Re: shelve non-transparency

    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

    Comment

    Working...