[ZODB-Dev] ZODB _v_ attributes are tricky

Neil Schemenauer nas at mems-exchange.org
Fri Apr 2 12:32:35 EST 2004


On Fri, Apr 02, 2004 at 11:48:42AM -0500, Shane Hathaway wrote:
> IMHO, _v_ attributes ought to be internal to ZODB.  Instead, ZODB ought 
> to provide two kinds of documented descriptors: Volatile and 
> TransactionalVolatile.  Volatile attributes revert to the default state 
> at any time; TransactionalVolatile attributes reliably revert to the 
> default state upon commit or rollback (including savepoint commit or 
> rollback).

This is what we like:

_Marker = object()

class ComputedAttribute(Persistent):
    """Computed attributes do not have any state that needs to be
    saved in the database.  Instead, their value is computed based
    on other persistent objects.  Although they have no real
    persistent state, they do have OIDs.  That allows synchronize of
    the cached value between connections (necessary to maintain
    consistency).  If the value becomes invalid in one connection
    then it must be invalidated in all connections.  That is
    achieved by marking the object as dirty and treating it like a
    normal persistent object.
    """

    def __getstate__(self):
        return None

    def __setstate__(self, state):
        assert state is None

    def invalidate(self):
        """Forget value and mark object as dirty.  On commit it
        will cause other connections to receive a invalidation
        notification and forget the value as well.
        """
        self.__dict__.clear()
        self._p_changed = 1

    def get(self, compute, ):
        """(compute) -> value

        Compute the value (if necessary) and return it.  'compute'
        needs to be a function that takes no arguments.
        """
        # we are careful here not to mark object as dirty
        d = self.__dict__
        value = d.get('value', _Marker)
        if value is _Marker:
            value = d['value'] = compute()
        return value


It's up to the application to call invalidation() when appropriate.
Well, we think we like it anyhow.  Maybe there is a flaw in the
design we missed.

  Neil



More information about the ZODB-Dev mailing list