Re: [lxml-dev] Copying an ElementTree doesn't work.
Hi John, John Krukoff wrote:
Quoting Stefan Behnel <behnel_ml@gkec.informatik.tu-darmstadt.de>:
John Krukoff wrote:
Can someone explain to me why when an ElementTree is copied, it's root element isn't copied?
import lxml.etree as etree import copy root = etree.XML( '<a/>' ) tree = copy.copy( etree.ElementTree( root ) ) tree.getroot( ) is None True
As ElementTrees are immutable, the above is not different from this:
tree = etree.ElementTree(root)
I'll add __copy__ and __deepcopy__, though, so that the above problem will disappear. So, thanks for reporting this.
For what it's worth, the use case is that I have an element tree that I want to copy multiple times, before performing destructive changes to the copies. Currently, copying the contents of an element tree to another element tree is kind of clunky:
original = etree.ElementTree( etree.XML( '<a/>' ) ) copied = etree.ElementTree( copy.copy( original.getroot( ) ) )
which is why I was asking if the expected use is to always pass around elements and wrap them with element trees only when it was convient to use the element tree methods (XSLT being what I'm interested in).
So, thanks, the fix will make this look a little less ugly.
Ok, sure. Just for code clarity, you might still want to use deepcopy() instead of copy(), not everybody is necessarily aware of the fact that lxml implements them the same way. Note also that copying an ElementTree actually now produces a shallow copy of the ElementTree. The XML tree is not touched in this case. Here is the patch, BTW, in case you want to apply it yourself. It will be in lxml 1.0.3 and 1.1, which are expected not too late this month. Stefan Index: src/lxml/etree.pyx =================================================================== --- src/lxml/etree.pyx (Revision 30633) +++ src/lxml/etree.pyx (Arbeitskopie) @@ -395,6 +395,15 @@ """ return self._context_node + def __copy__(self): + return ElementTree(self._context_node) + + def __deepcopy__(self, memo): + if self._context_node is None: + return ElementTree() + else: + return ElementTree( self._context_node.__copy__() ) + property docinfo: """Information about the document provided by parser and DTD. This value is only defined for ElementTree objects based on the root node
participants (1)
-
Stefan Behnel