Stefan Behnel | 2 May 16:30

Re: Custom Elements question

Hi,

another bit of reasoning here.

Stefan Behnel wrote:
> Alex Klizhentas wrote:
>> I've extended the ElementBase object using the approach described in the
>> tutorial, but SubElement does not work as desired:
>>
>> class NodeBase(etree.ElementBase):
>>      def append(self,child):
>>  print "aaa"
>>  return etree.ElementBase.append(self,child)
>>
>> etree.SubElement(root,"child") #no "aaa" printed
> 
> That's because SubElement() does not call .append().
[...]
> SubElement() does not call .makeelement() either. It's implemented in plain C.

One important reason is that this allows lxml.etree to append the new libxml2
node at the C level *before* the decision is taken which Python class should
be used to represent it. This might have an impact on the class lookup if it
considers the parental relation when taking its decision (lxml.objectify does
that, for example).

But that's the only difference I can see between etree.SubElement() and your
Python implementation. And you could even work around it by doing something
like this:

def SubElement(parent, tag, attrib={}, **extra):
     attrib = attrib.copy()
     attrib.update(extra)
     element = parent.makeelement(tag, attrib)
     parent.append(element)
     del element
     return parent[-1]

However, you might want to avoid that if you know you won't need it, e.g. when
using the "namespace" or "default" lookup scheme.

Stefan

Gmane