ElementTree's Element substitution in Python 3
Terry Reedy
tjreedy at udel.edu
Fri Jul 24 15:45:36 EDT 2009
André wrote:
> I have a function to replace the content of an ElementTree Element by
> that of another one which works using Python 2 but not with Python 3.
> I get an assertion error. The function is as follows:
>
> def replace_element(elem, replacement):
> '''replace the content of an ElementTree Element by that of
> another
> one.
> '''
> elem.clear()
> elem.text = replacement.text
> elem.tail = replacement.tail
> elem.tag = replacement.tag
> elem.attrib = replacement.attrib
> elem[:] = replacement[:]
>
> The last line is problematic. For example, if I do the following
> program with Python2.5
> ###
> from xml.etree import ElementTree as et
>
> a = et.Element('a')
> b = et.SubElement(a, 'b')
> c = et.Element('c')
>
> a[:] = c[:]
> ###
> nothing of note happens - however, doing the same with Python 3.1, I
> get the following traceback:
>
> Traceback (most recent call last):
> File "test.py", line 7, in <module>
> a[:] = c[:]
> File "/usr/local/py3.1/lib/python3.1/xml/etree/ElementTree.py", line
> 210, in __setitem__
> assert iselement(element)
> AssertionError
>
> ======
> I would gladly welcome any suggestion for writing a replace_element()
> function that works with Python 3.1
My guess is that you found a subtle bug in the 3.1 version of
ElementTree, perhap a result of conversion. I would take a look at the
noted line 210 to see whether it is 'a' or 'c' that is not passing as an
element. Assuming that it is 'c', I would look at __getitem__ to see why
not. Is [:] special-cased? Compare the codes for 2.5 and 3.1. Assuming
it still looks like a bug, report it on the tracker using your minimal
example, leaving out your function.
tjr
More information about the Python-list
mailing list