En Mon, 28 Apr 2008 02:08:31 -0300, tarun <[EMAIL PROTECTED]> escribió:

> Hi All,
> I want to store the class instance object variables persistenlty in one file
> so that other file can also access for some filtering. I tired doing this
> using the shelve module.
>
> *Code:*
> class A:
>     pass
>
> import shelve
> filename = 'test.db'
> d = shelve.open(filename)
>
> a = A()
> print a
> d['1'] = a
>
> print d['1']
> d.close()
>
> *Output:*
> <__main__.A instance at 0x018B56C0>
> <__main__.A instance at 0x018B5760>
>
> *Observation:*
> I expect both the print statements to return the same value, The second
> print statement just reads the dictonary, but still the adress (0x..) is
> different from the first print statement. Can anyone tell me why. Also let
> me know if you the way of getting same value both the times.

By default, each time you do d['1'] you get a *different* object. A shelve 
isn't very smart: it stores a string representation of your object (using 
pickle) and each time you ask for the object, it unpickles the stored string. 
When used as a persistence mechanism, it doesn't matter so much, the process 
that created the original instance may have died eons ago.
If object identity is important to you, you should remember to "fetch" the 
values only once in a single process, or use the writeback=True argument to the 
shelve constructor. But read the warning at 
<http://docs.python.org/lib/module-shelve.html>

py> d = shelve.open(filename, writeback=True)
py> a = A()
py> d['1'] = a
py> x1 = d['1']
py> x2 = d['1']
py> x3 = d['1']
py> print a, x1
<__main__.A instance at 0x00A3D5D0> <__main__.A instance at 0x00A3D5D0>
py> a is x1 is x2 is x3
True

-- 
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to