Commits

Anonymous committed 9d39d4b

ported to python 2.7 / >= 3.3 using six

the port itself was half automated (using python-modernize) and half manual
fixes and cleanups.

  • Participants
  • Parent commits f35162d

Comments (0)

Files changed (6)

emeraldtree/ElementInclude.py

 ##
 
 import copy
-import ElementTree
+from . import ElementTree
 
 XINCLUDE = "{http://www.w3.org/2001/XInclude}"
 

emeraldtree/ElementPath.py

 ##
 
 import re
+import six
 
 xpath_tokenizer = re.compile(
     "("
     ).findall
 
 def prepare_tag(next, token):
-    from ElementTree import Element
+    from .ElementTree import Element
     tag = token[1]
     def select(context, result):
         for elem in result:
 
 def find(elem, path):
     try:
-        return findall(elem, path).next()
+        return next(findall(elem, path))
     except StopIteration:
         return None
 
         if path[:1] == "/":
             raise SyntaxError("cannot use absolute path on element")
         stream = iter(xpath_tokenizer(path))
-        next = stream.next
-        token = next()
+        token = next(stream)
         selector = []
         while 1:
             try:
-                selector.append(ops[token[0]](next, token))
+                selector.append(ops[token[0]](lambda: next(stream), token))
             except StopIteration:
                 raise SyntaxError("invalid path")
             try:
-                token = next()
+                token = next(stream)
                 if token[0] == "/":
-                    token = next()
+                    token = next(stream)
             except StopIteration:
                 break
         _cache[path] = selector
 
 def findtext(elem, path, default=None):
     try:
-        elem = findall(elem, path).next()
+        elem = next(findall(elem, path))
         return elem.text
     except StopIteration:
         return default

emeraldtree/html.py

 # Tools to build element trees from HTML files.
 ##
 
-import htmlentitydefs
-from HTMLParser import HTMLParser as HTMLParserBase
-
 from . import tree
+import six
+from six.moves import html_entities
+from six.moves import html_parser
+HTMLParserBase = html_parser.HTMLParser
 
 
 ##
     # (Internal) Handles entity references.
 
     def handle_entityref(self, name):
-        entity = htmlentitydefs.entitydefs.get(name)
+        entity = html_entities.entitydefs.get(name)
         if entity:
             if len(entity) == 1:
                 entity = ord(entity)
     # (Internal) Handles character data.
 
     def handle_data(self, data):
-        if isinstance(data, str):
+        if isinstance(data, six.binary_type):
             # convert to unicode, but only if necessary
-            data = unicode(data, self.encoding, "ignore")
+            data = data.decode(self.encoding, "ignore")
         self.__builder.data(data)
 
     ##

emeraldtree/tests/test_html.py

 import py.test
 
 from .. import html, tree
+import six
+from six import StringIO
 
 def serialize(elem, method):
-    from StringIO import StringIO
     file = StringIO()
     elem.write(file.write, method=method)
     return file.getvalue()
     assert isinstance(elem, tree.Element)
     assert len(elem) == 1
     assert elem[0] == 'b'
-    assert isinstance(elem[0], unicode)
+    assert isinstance(elem[0], six.text_type)
 
 def test_read_text2():
     elem = html.HTML('<a>b<c>d</c>d</a>')

emeraldtree/tests/test_tree.py

 import py.test
 from emeraldtree.tree import *
+import six
+from six import StringIO
 
 def serialize(elem, namespaces={}):
-    from StringIO import StringIO
     file = StringIO()
     elem.write(file.write, namespaces=namespaces)
     return file.getvalue()
     qname = QName(u'a')
     assert qname.uri is None
     assert qname.name == u'a'
-    assert isinstance(qname.name, unicode)
-    assert unicode(qname) == u'a'
+    assert isinstance(qname.name, six.text_type)
+    assert six.text_type(qname) == u'a'
 
     qname = QName(u'{b}a')
     assert qname.uri == u'b'
-    assert isinstance(qname.uri, unicode)
+    assert isinstance(qname.uri, six.text_type)
     assert qname.name == u'a'
-    assert unicode(qname) == u'{b}a'
+    assert six.text_type(qname) == u'{b}a'
 
     qname = QName(u'a', u'b')
     assert qname.uri == u'b'
     assert qname.name == u'a'
-    assert unicode(qname) == u'{b}a'
+    assert six.text_type(qname) == u'{b}a'
 
     py.test.raises(ValueError, QName, u'{bau')
     py.test.raises(ValueError, QName, u'{b}a', u'c')
     assert isinstance(elem, Element)
     assert len(elem) == 1
     assert elem[0] == u'b'
-    assert isinstance(elem[0], unicode)
+    assert isinstance(elem[0], six.text_type)
 
 def test_XMLParser_text2():
     elem = XML(u'<a>b<c>d</c>d</a>')

emeraldtree/tree.py

 # OF THIS SOFTWARE.
 
 from __future__ import generators
+import six
 
 __all__ = [
     # public symbols
 # structure, and convert it from and to XML.
 ##
 
-import ElementPath
+from . import ElementPath
 
 class ParseError(SyntaxError):
     pass
 
     @property
     def text(self):
-        if len(self) and isinstance(self[0], basestring):
+        if len(self) and isinstance(self[0], six.string_types):
             return self[0]
 
     ##
     def __len__(self):
         return len(self._children)
 
-    def __nonzero__(self):
+    def __bool__(self):
         return True
+    __nonzero__ = __bool__
 
     ##
     # Returns the given subelement.
             if isinstance(e, Element):
                 for s in e.itertext():
                     yield s
-            elif isinstance(e, basestring):
+            elif isinstance(e, six.string_types):
                 yield e
 
     def iter_elements(self):
 
 PI = ProcessingInstruction
 
-class QName(unicode):
+class QName(six.text_type):
     """
     QName wrapper.  This can be used to wrap a QName attribute value, in
     order to get proper namespace handling on output.
     __slots__ = 'name', 'uri'
 
     def __new__(cls, name, uri=None):
-        text = name = unicode(name)
+        text = name = six.text_type(name)
 
         if name[0] == '{':
             if uri is not None:
             name = name[i + 1:]
 
         if uri is not None:
-            uri = unicode(uri)
+            uri = six.text_type(uri)
             text = '{' + uri + '}' + name
 
-        ret = unicode.__new__(cls, text)
-        unicode.__setattr__(ret, 'name', name)
-        unicode.__setattr__(ret, 'uri', uri)
+        ret = six.text_type.__new__(cls, text)
+        six.text_type.__setattr__(ret, 'name', name)
+        six.text_type.__setattr__(ret, 'uri', uri)
 
         return ret
 
     def feed(self, data):
         try:
             self._parser.Parse(data, 0)
-        except self._error, v:
+        except self._error as v:
             self._raiseerror(v)
 
     ##
     def close(self):
         try:
             self._parser.Parse("", 1) # end of data
-        except self._error, v:
+        except self._error as v:
             self._raiseerror(v)
         tree = self.target.close()
         del self.target, self._parser # get rid of circular references
                 tag = elem.tag
                 if isinstance(tag, QName):
                     add_qname(tag)
-                elif isinstance(tag, basestring):
+                elif isinstance(tag, six.string_types):
                     add_qname(QName(tag))
                 elif tag is not None:
                     self._raise_serialization_error(tag)
 
-                for key in elem.attrib.iterkeys():
+                for key in six.iterkeys(elem.attrib):
                     if isinstance(key, QName):
                         add_qname(key)
-                    elif isinstance(key, basestring):
+                    elif isinstance(key, six.string_types):
                         add_qname(QName(key))
                     elif key is not None:
                         self._raise_serialization_error(key)
         """create a attribute string from a dict d"""
         if not d:
             return u''
-        items = d.items()
-        items.sort(key=lambda x: x[0])
+        items = sorted(d.items(), key=lambda x: x[0])
         result = []
         for k, v in items:
             k = qnames[k]
             if isinstance(v, QName):
                 v = qnames[v]
             else:
-                v = self._escape_attrib(unicode(v))
+                v = self._escape_attrib(six.text_type(v))
             # FIXME: handle boolean attributes for HTML
             result.append(u' %s="%s"' % (k, v))
         return u''.join(result)
         """create a namespace string from a dict d"""
         if not d:
             return u''
-        items = d.items()
-        items.sort(key=lambda x: x[1]) # sort on prefix
+        items = sorted(d.items(), key=lambda x: x[1]) # sort on prefix
         result = []
         for v, k in items:
             if k:
         write(u"<?%s?>" % text)
 
     def _serialize_cdata(self, write, elem):
-        write(self._escape_cdata(unicode(elem)))
+        write(self._escape_cdata(six.text_type(elem)))
 
     def serialize(self, write, elem, qnames, namespaces={}):
         if isinstance(elem, Element):