[lxml-dev] ElementTree.find does not accept QName objects.

John Krukoff jkrukoff at ltgc.com
Tue Apr 1 22:24:22 CEST 2008


Okay, that's weird. I knew that I'd been able to use QName's with ET in
that past, but when I double checked I found that it didn't work for me.
It looks like I just managed to hit some magic special case in ET to
make this work at all, as this works:

Python 2.5.1 (r251:54863, Jan  8 2008, 15:02:32) 
[GCC 4.1.2 (Gentoo 4.1.2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from elementtree import ElementTree
>>> x = ElementTree.XML( '<a><b/></a>' )
>>> x.find( 'b' )
<Element b at b7c90b0c>
>>> x.find( ElementTree.QName( 'b' ) )
<Element b at b7c90b0c>

But this doesn't:

Python 2.5.1 (r251:54863, Jan  8 2008, 15:02:32) 
[GCC 4.1.2 (Gentoo 4.1.2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from elementtree import ElementTree
>>> x = ElementTree.XML( '<a><b/></a>' )
>>> x.find( ElementTree.QName( 'b' ) )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/site-packages/elementtree/ElementTree.py",
line 327, in find
    return ElementPath.find(self, path)
  File "/usr/lib/python2.5/site-packages/elementtree/ElementPath.py",
line 183, in find
    return _compile(path).find(element)
  File "/usr/lib/python2.5/site-packages/elementtree/ElementPath.py",
line 173, in _compile
    p = Path(path)
  File "/usr/lib/python2.5/site-packages/elementtree/ElementPath.py",
line 69, in __init__
    tokens = xpath_tokenizer(path)
TypeError: expected string or buffer

It looks like it only works when ET.find has already been called with
the string value of the same name that a following QName find specifies.
Some internal caching, perhaps?

In any case, it does look like accepting QNames at all is a bug in ET,
or at least an accident. Don't know what that means for lxml, but it
would seem to me that strict compatibility would mean that find should
be restricted to strings.

As for my use case, I suppose I can always just wrap all my find
parameters with str to make it work.

On Sat, 2008-03-29 at 11:42 +0100, Stefan Behnel wrote:
> Hi,
> 
> John Krukoff wrote:
> > Since I was the one that complained about the find method on Elements
> > not accepting QNames, it's probably not surprising that I expected them
> > to work with the ElementTree find method as well. Instead an unsliceable
> > error is thrown, due to the value being expected to be a string
> 
> Sure, here's the obvious patch.
> 
> BTW, I expect ET to have the same problem here.
> 
> Stefan
> 
-- 
John Krukoff <jkrukoff at ltgc.com>
Land Title Guarantee Company



More information about the lxml-dev mailing list