By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,364 Members | 1,580 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,364 IT Pros & Developers. It's quick & easy.

Re: Related to Shelve Module

P: n/a
En Mon, 28 Apr 2008 02:08:31 -0300, tarun <ta**********@gmail.comescribió:
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>

pyd = shelve.open(filename, writeback=True)
pya = A()
pyd['1'] = a
pyx1 = d['1']
pyx2 = d['1']
pyx3 = d['1']
pyprint a, x1
<__main__.A instance at 0x00A3D5D0<__main__.A instance at 0x00A3D5D0>
pya is x1 is x2 is x3
True

--
Gabriel Genellina

Jun 27 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.