[Zope] persistent object with non-persistent attributes

Dylan Reinhardt zope@dylanreinhardt.com
Tue, 04 Mar 2003 08:19:39 -0800


At 01:22 AM 3/4/2003, Jerome Alet wrote:
>I would like to create a python Zope product which allows me
>to create persistent objects.
>
>but these objects have (as subobjects ?) complex attributes which
>are themselves instances of a non-Zope related class, and which
>should not be persistent (think hardware plug&play), because
>they are recreated every time a method is called on my instance.

Luckily for you, they won't be persisted unless you ask them to 
be.   That's far better than the normal case where you *want* them 
persisted but they aren't. :-)


>I think I could do (untested) :
>
>   myZopePersistentClassInstance.complexAttr = myNonZopeClass()
>
>but this will probably, if it works, bloat by ZODB.

In this case, that isn't what you want.  Since you want the instances *not* 
to persist, don't use any of Zope's persistent subobjects.

Let's say you have an instance of your product A, which contains subobjects 
B and C.  You want A.B to persist but A.C to be "volatile" and revert to a 
particular value.  Here goes:

----------------

class my_product(various_base_classes):
    def __init__(self, **args):
       self.B = my_module.my_class()

    C = another_module.another_class()

    def first_method(self):
       self.B  = self.do_something()
       self._p_changed = 1

    def second_method(self):
       self.C = self.do_something_else()

----------------

The magic assignment self._p_changed=1 triggers the persistence machinery 
to update its copy of your instance, recording any changes that have been 
made to your subobjects.  The save happens at the end of the transaction 
and only needs to be called once per transaction... though more times 
aren't going to break anything.  After a reload or restart, the value of 
A.C will probably revert to the class value for C... though if you were to 
change both objects in one transaction, the new value of C will get 
persisted as an instance variable.

This is sort of a trivial example, but if you dig a bit deeper, you can 
exercise much finer-grained control over the whole thing.

HTH,

Dylan