[lxml-dev] Context of custom XPath functions

Stefan Behnel stefan_ml at behnel.de
Thu Aug 23 12:42:56 CEST 2007


Hi,

Frederik Elwert wrote:
> Currently, I'm trying to implement some of the XForms functions with
> lxml. The most urgent one is instance(), which gets the instance data
> from an XForms model. But if you're not familiar with XForms, don't
> bother, just think of id() or something similar:
> 
> With id(), it is necessary to access the context of the function call,
> i.e., the tree in which it is called. id() is supposed to return an
> element node (or node-set) matching the given argument. So id() has to
> know about the tree, and not only about it's given argument.

I assume that instance() does not get any nodes as parameter. Otherwise you
could call their getroottree() to retrieve the ElementTree of the current
document.


> So how would one implement id() or any similar function with lxml? As
> far as I got with custom functions, they only can handle the arguments
> they get passed direcly, but they don't know about the broader context.
> Any suggestions how I could solve this?

One way would be to define the functions local to each XPath call and provide
them with the necessary context yourself.

If you want a more global solution, you may have noticed that functions
receive a (currently empty) context object as first parameter. Maybe we should
make that a real context object or a dictionary that includes the reference to
the current document or its root node?

Stefan



More information about the lxml-dev mailing list