O'Reilly logo

Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft, Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.12. Checking an Instance for Any State Changes

Credit: David Hughes

Problem

You need to check whether any changes to an instance's state have occurred to selectively save instances that have been modified since the last "save" operation.

Solution

An effective solution is a mixin class—a class you can multiply inherit from and that is able to take snapshots of an instance's state and compare the instance's current state with the last snapshot to determine whether or not the instance has been modified:

import copy class ChangeCheckerMixin(object): containerItems = {dict: dict.iteritems, list: enumerate} immutable = False def snapshot(self): ''' create a "snapshot" of self's state -- like a shallow copy, but recursing over container types (not over general instances: instances must keep track of their own changes if needed). ''' if self.immutable: return self._snapshot = self._copy_container(self._ _dict_ _) def makeImmutable(self): ''' the instance state can't change any more, set .immutable ''' self.immutable = True try: del self._snapshot except AttributeError: pass def _copy_container(self, container): ''' semi-shallow copy, recursing on container types only ''' new_container = copy.copy(container) for k, v in self.containerItems[type(new_container)](new_container): if type(v) in self.containerItems: new_container[k] = self._copy_container(v) elif hasattr(v, 'snapshot'): v.snapshot( ) return new_container def isChanged(self): ''' True if self's state is changed since the last snapshot ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required