[Python-checkins] cpython (3.3): Issue #17011: Fix caching of xpath path when namespaces are present.

eli.bendersky python-checkins at python.org
Sun Aug 4 02:49:01 CEST 2013


http://hg.python.org/cpython/rev/854ded9135c2
changeset:   85005:854ded9135c2
branch:      3.3
parent:      85003:7b023134ad83
user:        Eli Bendersky <eliben at gmail.com>
date:        Sat Aug 03 17:47:47 2013 -0700
summary:
  Issue #17011: Fix caching of xpath path when namespaces are present.

Thanks to Stefan Behnel for the report and proposed solution & test.

files:
  Lib/test/test_xml_etree.py   |  14 ++++++++++++++
  Lib/xml/etree/ElementPath.py |   6 ++++--
  2 files changed, 18 insertions(+), 2 deletions(-)


diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -1679,6 +1679,20 @@
             summarize_list(e.findall(".//{http://effbot.org/ns}tag")),
             ['{http://effbot.org/ns}tag'] * 3)
 
+    def test_findall_different_nsmaps(self):
+        root = ET.XML('''
+            <a xmlns:x="X" xmlns:y="Y">
+                <x:b><c/></x:b>
+                <b/>
+                <c><x:b/><b/></c><y:b/>
+            </a>''')
+        nsmap = {'xx': 'X'}
+        self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 2)
+        self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2)
+        nsmap = {'xx': 'Y'}
+        self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 1)
+        self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2)
+
     def test_bad_find(self):
         e = ET.XML(SAMPLE_XML)
         with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'):
diff --git a/Lib/xml/etree/ElementPath.py b/Lib/xml/etree/ElementPath.py
--- a/Lib/xml/etree/ElementPath.py
+++ b/Lib/xml/etree/ElementPath.py
@@ -246,10 +246,12 @@
 
 def iterfind(elem, path, namespaces=None):
     # compile selector pattern
+    cache_key = (path, None if namespaces is None
+                            else tuple(sorted(namespaces.items())))
     if path[-1:] == "/":
         path = path + "*" # implicit all (FIXME: keep this?)
     try:
-        selector = _cache[path]
+        selector = _cache[cache_key]
     except KeyError:
         if len(_cache) > 100:
             _cache.clear()
@@ -269,7 +271,7 @@
                     token = next()
             except StopIteration:
                 break
-        _cache[path] = selector
+        _cache[cache_key] = selector
     # execute selector pattern
     result = [elem]
     context = _SelectorContext(elem)

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list