[Tutor] updating shelved record
Magnus Lyckå
magnus@thinkware.se
Sun Jul 6 19:50:02 2003
I've never used shelve for anything real, but I suspect
that you need to rebind dbase['brian'], like this:
brian = dbase['brian']
brian['age'] = 44
dbase['brian'] = brian
I suspect that "dbase['brian']" will return a copy of what
is in the shelve, and in your code below, you update this
copy and then throw it away, since you have no references
to it.
Do you understand what I mean? What you are doing is a bit
like doing s.upper() instead of s = s.upper() if you want
to convert a string s to upper case.
To understand what I mean you must understant the difference
between names and objects in Python.
There are probably neater alternatives to shelve. Have a
look at...
http://www-106.ibm.com/developerworks/library/l-pypers.html
and
http://www.thinkware.se/cgi-bin/thinki.cgi/PersistenceSystems
At 17:29 2003-07-06 -0600, Joseph Paish wrote:
>i am trying to update a file "in place" using shelve.
>
>this is what i have so far, using an example i found in a book to build the
>original database in order to test ideas an my understanding of how shelve
>works :
>
>
>Python 2.0 (#1, Apr 11 2001, 19:18:08)
>[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386
>Type "copyright", "credits" or "license" for more information.
>IDLE 0.6 -- press F1 for help
>
> >>> import shelve
> >>> dbase = shelve.open("mydbase")
> >>> object1 = ['The', 'bright', ('side', 'of'), ['life']]
> >>> object2 = {'name': 'Brian', 'age': 33, 'motto': object1}
> >>> dbase['brian'] = object2
> >>> dbase.close()
>
> >>> import shelve
> >>> dbase = shelve.open("mydbase")
> >>> dbase['brian']
>{'age': 33, 'name': 'Brian', 'motto': ['The', 'bright', ('side', 'of'),
>['life']]}
> >>> dbase['brian']['age']
>33
>
># okay so far
>
> >>> dbase.close()
> >>> dbase = shelve.open("mydbase")
> >>> print dbase['brian']['age']
>33
>
># try and change brian's age to 44
> >>> dbase['brian']['age'] = '44'
> >>> print dbase['brian']['age']
>33
># no luck
>
># try closing and re-opening the file to force a flush and hopefully commit
>the change.
> >>> dbase.close()
> >>> dbase = shelve.open("mydbase")
> >>> print dbase['brian']['age']
>33
>
># brian still 33 years old.
>
>
>i guess the question is "how can i change brian's age on disk?". i must be
>missing something very obvious.
>
>thanks
>
>joe
>
>ps. i have stripped out a lot of the IDLE session (mainly errors), but
>nothing that impacts what i am trying to do.
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language