Python object persistency using pickle...

David CROSSON david.crosson at vx.cit.alcatel.fr
Tue Sep 28 03:12:28 EDT 1999


Hello,
    I'm relatively new to python language and currently testing some of
its features.
I read inside the documentation that object persistency using pickle
module can
handle :

- recursive objects (objects containing references to themselves)
- object sharing (references to the same object in different places)
- user-defined classes and their instances

So I made a simple test with 2 objects instances of a class A, each
of those instances contain a reference to a third object instance of a
class B.
When I restore those objects, instead of getting only one B instance,
I got three instances !!! So I wonder how I can make the object sharing
feature working ?

The code is attached to this email.

Thanks for all.


--
// David Crosson - Software Engineer
// Alcatel Telecom, Transmission Systems Division
// Phone: 01 6449 2985, Fax: 01 6449 2189
// mailto:david.crosson at vx.cit.alcatel.fr


-------------- next part --------------
#!/usr/bin/env python

import pickle

class A:
    name='My name is James'
    bref=0
    x=0
    def f(self,v): self.x=v

class B:
    name='My name is Bond'
    def hello(self): print 'Hello World ', self.name


def save():
    b=B()
    a1=A()
    a2=A()
    
    a1.bref=b
    a2.bref=b
    a1.f(1)
    a2.f(2)

    b.name='Yearr';

    a1.bref.hello()
    print a1.x, a2.x
    print a1,a1.bref
    print a2,a2.bref
    print b

    f1=open("f1","w")
    f2=open("f2","w")
    f3=open("f3","w")

    pickle.dump(b,f3)
    pickle.dump(a1,f1)
    pickle.dump(a2,f2)


def restore():
    f1=open("f1","r")
    f2=open("f2","r")
    f3=open("f3","r")

    b=pickle.load(f3)
    a1=pickle.load(f1)
    a2=pickle.load(f2)

    a1.bref.hello()
    print a1.x, a2.x
    print a1,a2,b
    print a1,a1.bref
    print a2,a2.bref
    print b

#save()
restore()

# PB-> Plusieurs instances de B sont restorees !!!!


More information about the Python-list mailing list