how to detect change of list of instances

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Mar 14 03:11:50 CET 2007


On Tue, 13 Mar 2007 18:23:24 -0700, manstey wrote:

> how do I detect a change in a list of class instances?
> 
> from copy import deepcopy
> 
> class CaListOfObj(list):
>     """ subclass of list """
>     def __init__(self, *args, **kwargs):
>         list.__init__(self, *args, **kwargs)
> 
> class CaClass(object):
>     pass
> 
> class CaData(object):
>     pass

CaData has no equality test defined, so by default equality falls back on
identity tests.


> myclass=CaClass()

myclass is named badly. It isn't a class, it is an instance.



> a=CaData()
> b=CaData()
> c=CaData()
> 
> listInstances = CaListOfObj([a,b,c])
> setattr(myclass,'initlist',listInstances)
> setattr(myclass,'newlist',deepcopy(listInstances))

An easier, more readable, way to do that is just this:

myclass.initlist = listInstances
myclass.newlist = deepcopy(listInstances)



> print myclass.initlist == myclass.newlist
> myclass.newlist.append(c)
> print myclass.initlist == myclass.newlist
> 
> gives
> False
> False
> 
> because deep copies of instances are different instances. what I want
> to do is detect a change between .initlist and .newlist.

You need to define what "equal" means for two different instances of
CaData, otherwise it will fall back on checking to see if they are the
same instance.



-- 
Steven D'Aprano 




More information about the Python-list mailing list