ElementTree's Element substitution in Python 3

Piet van Oostrum piet at cs.uu.nl
Fri Jul 24 15:17:10 EDT 2009


>>>>> André <andre.roberge at gmail.com> (A) a écrit:

>A> I have a function to replace the content of an ElementTree Element by
>A> that of another one which works using Python 2 but not with Python 3.
>A> I get an assertion error.  The function is as follows:

>A> def replace_element(elem, replacement):
>A>     '''replace the content of an ElementTree Element by that of
>A> another
>A>        one.
>A>     '''
>A>     elem.clear()
>A>     elem.text = replacement.text
>A>     elem.tail = replacement.tail
>A>     elem.tag = replacement.tag
>A>     elem.attrib = replacement.attrib
>A>     elem[:] = replacement[:]

>A> The last line is problematic.  For example, if I do the following
>A> program with Python2.5
>A> ###
>A> from xml.etree import ElementTree as et

>A> a = et.Element('a')
>A> b = et.SubElement(a, 'b')
>A> c = et.Element('c')

>A> a[:] = c[:]
>A> ###
>A> nothing of note happens - however, doing the same with Python 3.1, I
>A> get the following traceback:

>A> Traceback (most recent call last):
>A>   File "test.py", line 7, in <module>
>A>     a[:] = c[:]
>A>   File "/usr/local/py3.1/lib/python3.1/xml/etree/ElementTree.py", line
>A> 210, in __setitem__
>A>     assert iselement(element)
>A> AssertionError

This is a Python bug. Please report it. The problem is that in Python 3
slice assignments are done with __setitem__ rather than __setslice__ but
ElementTree has not been adapted to that.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list