object persistency, store instances relationship externally

Discussion in 'Python' started by King, Jul 25, 2008.

  1. King

    King Guest

    This is a new test for object persistency. I am trying to store the
    relationship between instances externally.
    It's not working as expected. May be I am doing it in wrong way. Any
    suggestions?


    import shelve

    class attrib(object):
    pass

    class node(object):
    def __init__(self):
    self.a = attrib()
    self.b = attrib()
    self.c = attrib()
    self.d = attrib()

    a = node()
    #store pair relationship. This relationship is created at run time.
    lst = [[a.a, a.b], [a.c, a.d]]
    #Write objects into file
    shelf = shelve.open('shelve_test_01.txt', writeback=True)
    shelf['node'] = a
    shelf['lst'] = lst
    shelf.sync()
    shelf.close()


    #Read objects from file
    shelf = shelve.open('shelve_test_01.txt', 'r')
    a = shelf['node']
    lst = shelf['lst']
    print a.a, a.b, a.c, a.d
    #lst does not contains the relationship of object 'a''s attributes,
    instead it's creating new instances
    #of 'attrib' class
    print lst
    King, Jul 25, 2008
    #1
    1. Advertising

  2. King wrote:

    > This is a new test for object persistency. I am trying to store the
    > relationship between instances externally.
    > It's not working as expected. May be I am doing it in wrong way. Any
    > suggestions?


    The shelve module pickles each stored item individually. To preserve
    inter-object relations, try putting all related things in a tuple, and
    store that instead. E.g.

    shelf['data'] = (a, lst)

    a, lst = shelf['data']

    </F>
    Fredrik Lundh, Jul 25, 2008
    #2
    1. Advertising

  3. King

    King Guest

    Thanks Fredrik,

    It helped a lot and this is really an amazing this I have discovered
    today. :))
    King, Jul 25, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. davout
    Replies:
    0
    Views:
    360
    davout
    Sep 8, 2004
  2. Robert Buck
    Replies:
    0
    Views:
    438
    Robert Buck
    Feb 24, 2004
  3. Batista, Facundo

    Auto persistency

    Batista, Facundo, Aug 5, 2003, in forum: Python
    Replies:
    2
    Views:
    279
    Timo Warns
    Aug 7, 2003
  4. Mauro

    Persistency problem

    Mauro, May 10, 2007, in forum: Java
    Replies:
    1
    Views:
    283
    Tom Hawtin
    May 10, 2007
  5. Christophe Poucet

    Concerning persistency techniques

    Christophe Poucet, Sep 29, 2005, in forum: Ruby
    Replies:
    3
    Views:
    76
    Dave Burt
    Sep 29, 2005
Loading...

Share This Page