Python elementtree and mutability -
what doing wrong python (2.7) here?
i using element trees store xml data. class constructor takes class instance element tree attribute (sw class insance, sw.instance element tree) parameter, adds element , stores in class variable self.software. class constructor:
import xml.etree.elementtree elt class myclass(object): def __init__(self, bd, sw, name): itmp = sw.instance print "before %s" % elt.tostring(itmp) y = elt.subelement(itmp, "name") y.text = name self.software = itmp print "after %s" % elt.tostring(sw.instance) the problem is, in addition of storing modified sw self.software, changes sw.instance. when use create 2 classes
foo = myclass(x, mysoftwareclass, "foo") bar = myclass(y, mysoftwareclass, "bar") the foo instance fine bar instance contains 2 "name" elements. first call myclass appears modify mysoftwareclass instance. have confirmed before , after print statements.
i sort of thought mysoftwareclass immutable when called this. can of course use workaround , create 2 identical software class instances, pass 1 foo , 1 bar, curious happens here.
found it. copy.deepcopy. how stupid of me.
Comments
Post a Comment