Merge pull request #185 from Jorick/master
[rainbowstream.git] / rainbowstream / py3patch.py
index 83e5f0a1845bc4d781d2192a10f66ba71c77e208..7e71e2a04fa897f282e4e53bf0a0a0c0c42d3c89 100644 (file)
@@ -1,27 +1,28 @@
-"""
-  Python 3 supports
-"""
 import sys
 
-# StringIO module
-try:
-    from StringIO import StringIO, BytesIO
-except:
-    from io import StringIO, BytesIO
+# Library compatibility
+if sys.version[0] == "2":
+    from HTMLParser import HTMLParser
+    from urllib2 import URLError
+else:
+    from html.parser import HTMLParser
+    from urllib.error import URLError
 
-# HTMLParser module
+unescape = HTMLParser().unescape
+# According to https://github.com/python/cpython/blob/master/Lib/html/parser.py#L547 ,
+# in python 3.5 maybe I should use
+# from html import unescape
+# but it is a far-future story:)
 
-try:
-    from HTMLParser import HTMLParser
-    def unescape(s):
-        p = HTMLParser()
-        return p.unescape(s)
-except:
-    from html import unescape
 
-# raw_input and map functiion behaviour
-if sys.version[0] == "3":
+# Function compatibility
+# xrange, raw_input, map ,unicde
+if sys.version[0] == "2":
+    lmap = lambda f, a: map(f, a)
+    str2u = lambda x: x.decode('utf-8')
+    u2str = lambda x: x.encode('utf-8')
+else:
+    xrange = range
     raw_input = input
     lmap = lambda f, a: list(map(f, a))
-else:
-    lmap = lambda f, a: map(f, a)
+    str2u = u2str = lambda x: x