automatic (un-)pickling / overwriting self

Alex Martelli aleax at aleax.it
Fri Mar 7 10:42:08 EST 2003


Clemens Hermann wrote:

> Hi,
> 
> while working on a cgi-admin interface i got a little problem with
> pickle.
> I use a hierarchical class structure to keep users, permissions, etc.
> As the amount of data is quite small i just pickle the top class
> instance that references the rest.

So far so good...

> I am looking for a way to automatically pickle the top class whenever
> one of the referenced object changes.

That's pretty hard indeed, to put it mildly; you'd basically have
to wrap every "referenced object" into the Observed side of an
Observed/Observer patter, catch EVERY change (a VERY tall order
indeed, with the amount of indirections being unbounded) and do
a callback to the top-class Observer.  I would urge you to look
for a much easier and less-general approach.

> Furthermore I want a class
> instance to unpickle the data automatically on creation.
> A self = unpickledObject in __init__ does not work (probably a bad
> idea anyway :).

You can code the class's __new__ method to return the unpickled
object, and leave its __init__ empty (it's called anyway after
__new__, unless you go for custom metaclasses or play some
strange tricks such as returning something that's NOT actually
an instance of that class).

> So how is automatic/implicite serialization(on changes) and

Too hard to bother with in the general case, IMHO.

> de-derialization(in __init__) from *within* a class instance done?
> Furthermore: How can I make sure that there can only be one instance
> of the top class active at a time?

You want the Singleton design pattern -- but it's not a good idea,
use Borg instead (let there be as many instances as there happen
to be, as long as they all share the same state).  See for example
http://www.aleax.it/Python/5ep.html for an in-depth essay on that.


Alex





More information about the Python-list mailing list