Update with pickle
Matteo Dell'Amico
della at toglimi.linux.it
Wed May 26 17:09:44 EDT 2004
Nicolas Fleury wrote:
> I just added a feature request on sf to have an updating load function
> in pickle. My preferred solution for now might still be the copy of
> __dict__ (I could copy slots also), it's simple and not intrusive (using
> proxies is, even if less a hack). However, the cleanest solution would
> be to implement your solution, but I have no idea how to do it for now.
Leif is essentially proposing a non-transparent proxy, while the
cookbook recipe I pointed out is a transparent proxy (i.e. you are using
a proxy, but you can access it just as if it was the original object).
If I understood correctly, you want something like this:
>>> pickle.dump(42, 'file')
>>> foo = foo2 = 'foo'
>>> pickle.update(foo, 'file')
>>> foo
42
>>> foo2
42
Well, it's not possible: variables are just names attached to objects,
and while you can assign a name to an object, you *can't* change the
object's type, or replace an object with another one.
And I think that copying __dict__ is a hack: it wouldn't work, for
instance, with builtin types, when __slots__ are used, or when you are
using properties.
With a proxy you could do something like this:
>>> foo = proxy(foo)
(use foo just as before)
>>> pickle.dump(foo._obj, 'file')
and then resume the file with
>>> foo._obj = pickle.load('file')
A transparent proxy is a clean way to do it: through delegation, it
would work with any kind of object, changes in code are localized in the
load/save part, and the rest of the application wouldn't even notice.
--
Ciao,
Matteo
More information about the Python-list
mailing list