compat.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import sys
  2. if sys.version_info < (3,):
  3. def isbasestring(s):
  4. return isinstance(s, basestring)
  5. def open_utf8(filename, mode):
  6. return open(filename, mode)
  7. def byte_to_str(x):
  8. return str(ord(x))
  9. import cStringIO
  10. def StringIO():
  11. return cStringIO.StringIO()
  12. def encode_utf8(x):
  13. return x
  14. def decode_utf8(x):
  15. return x
  16. def iteritems(d):
  17. return d.iteritems()
  18. def itervalues(d):
  19. return d.itervalues()
  20. def escape_string(s):
  21. if isinstance(s, unicode):
  22. s = s.encode("ascii")
  23. result = ""
  24. for c in s:
  25. if not (32 <= ord(c) < 127) or c in ("\\", '"'):
  26. result += "\\%03o" % ord(c)
  27. else:
  28. result += c
  29. return result
  30. def qualname(obj):
  31. # Not properly equivalent to __qualname__ in py3, but it doesn't matter.
  32. return obj.__name__
  33. else:
  34. def isbasestring(s):
  35. return isinstance(s, (str, bytes))
  36. def open_utf8(filename, mode):
  37. return open(filename, mode, encoding="utf-8")
  38. def byte_to_str(x):
  39. return str(x)
  40. import io
  41. def StringIO():
  42. return io.StringIO()
  43. import codecs
  44. def encode_utf8(x):
  45. return codecs.utf_8_encode(x)[0]
  46. def decode_utf8(x):
  47. return codecs.utf_8_decode(x)[0]
  48. def iteritems(d):
  49. return iter(d.items())
  50. def itervalues(d):
  51. return iter(d.values())
  52. def charcode_to_c_escapes(c):
  53. rev_result = []
  54. while c >= 256:
  55. c, low = (c // 256, c % 256)
  56. rev_result.append("\\%03o" % low)
  57. rev_result.append("\\%03o" % c)
  58. return "".join(reversed(rev_result))
  59. def escape_string(s):
  60. result = ""
  61. if isinstance(s, str):
  62. s = s.encode("utf-8")
  63. for c in s:
  64. if not (32 <= c < 127) or c in (ord("\\"), ord('"')):
  65. result += charcode_to_c_escapes(c)
  66. else:
  67. result += chr(c)
  68. return result
  69. def qualname(obj):
  70. return obj.__qualname__