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
myclass=CaClass()
a=CaData()
b=CaData()
c=CaData()
listInstances = CaListOfObj([a,b,c])
setattr(myclass,'initlist',listInstances)
setattr(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.
thanks
> 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
All I want to know is whether the newlist, as a list of instances, is
modified. I thought equality was the way to go, but is there a simpler
way? How can I monitor the state of newlist and set a flag if it is
changed in anyway?
<thinking-out-loud>
Override the mutators - or just wrap them in a decorator. But I don't
know if it's "simpler". And FWIW, it won't catch modifications of
contained objects - only modifications of the list itself. So you'd also
need to wrap contained objects in an object that would itself detect all
changes and notify the container. Err... Looks like equality is the way
to go.
</thinking-out-loud>