Repository: stchris/untangle

Issue:
If an XML tag is a Python keyword SyntaxError is raised on access
Namely, I had this issue with a class tag.

My first thought is to use aliases for these.

Discussion:

Patch:
diff --git a/untangle.py b/untangle.py
index 1263056..6d1e966 100755
--- a/untangle.py
+++ b/untangle.py
@@ -14,6 +14,7 @@
  License: MIT License - http://www.opensource.org/licenses/mit-license.php
 """
 import os
+import keyword
 from xml.sax import make_parser, handler
 try:
     from StringIO import StringIO
@@ -133,6 +134,11 @@ class Handler(handler.ContentHandler):
         name = name.replace('-', '_')
         name = name.replace('.', '_')
         name = name.replace(':', '_')
+
+        # adding trailing _ for keywords
+        if keyword.iskeyword(name):
+            name += '_'
+
         attrs = dict()
         for k, v in attributes.items():
             attrs[k] = v


Test patch:
diff --git a/tests/tests.py b/tests/tests.py
index 76a1ef4..33558e3 100755
--- a/tests/tests.py
+++ b/tests/tests.py
@@ -93,6 +93,14 @@ class FromStringTestCase(unittest.TestCase):
 
         self.assertEqual('child1', getattr(o.root, 'child')[0]['name'])
 
+    def test_python_keyword(self):
+        o = untangle.parse("<class><return/><pass/><None/></class>")
+        self.assert_(o is not None)
+        self.assert_(o.class_ is not None)
+        self.assert_(o.class_.return_ is not None)
+        self.assert_(o.class_.pass_ is not None)
+        self.assert_(o.class_.None_ is not None)
+
 
 class InvalidTestCase(unittest.TestCase):
     """ Test corner cases """