[lxml-dev] Custom Elements

Stefan Behnel stefan_ml at behnel.de
Wed Mar 21 09:23:00 CET 2007


Stephan Richter wrote:
> class DirectiveLookup(etree.CustomElementClassLookup):
> 
>     def lookup(self, type, doc, namespace, name):
>         import pdb; pdb.set_trace()
>         if name == 'foo1':
>             return Directive1
>         elif name == 'foo2':
>             return Directive2
>         return None
> 
> However, in my case, the lookup also depends on the parent element in my case, 
> because a tag with the same name can have different meanings in different 
> contexts. (Don't ask, this is a specification requirement of RML. ;-)
> 
> So here my question: How do I access the parent element?

That's a tricky one. Providing the parent at the Python level would require
its instantiation as Element, i.e. another lookup of the target class. So we
end up with a recursive chicken-and-egg problem.

Providing its tag name might be enough, but then, others might need to check
its attributes or other parts of the tree, too - no end in sight.

So, all I can suggest is to write a separate Pyrex module against etree's
public C-API to provide a C-implemented lookup mechanism that works on the
libxml2 tree. You can take a look at objectify's ObjectifyElementClassLookup
implementation to see how this can be done. It's actually not difficult at
all, but you'd have to write it in Pyrex.

Another possible solution is to actually use the same class, but with a
different configuration based on its parent. You can do the setup in
Element._init().

Hope it helps,
Stefan


More information about the lxml-dev mailing list