py3k.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. Python 3 compatibility tools.
  3. """
  4. from __future__ import division, absolute_import, print_function
  5. __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
  6. 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
  7. 'asstr', 'open_latin1', 'long', 'basestring', 'sixu',
  8. 'integer_types']
  9. import sys
  10. if sys.version_info[0] >= 3:
  11. import io
  12. long = int
  13. integer_types = (int,)
  14. basestring = str
  15. unicode = str
  16. bytes = bytes
  17. def asunicode(s):
  18. if isinstance(s, bytes):
  19. return s.decode('latin1')
  20. return str(s)
  21. def asbytes(s):
  22. if isinstance(s, bytes):
  23. return s
  24. return str(s).encode('latin1')
  25. def asstr(s):
  26. if isinstance(s, bytes):
  27. return s.decode('latin1')
  28. return str(s)
  29. def isfileobj(f):
  30. return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter))
  31. def open_latin1(filename, mode='r'):
  32. return open(filename, mode=mode, encoding='iso-8859-1')
  33. def sixu(s):
  34. return s
  35. strchar = 'U'
  36. else:
  37. bytes = str
  38. long = long
  39. basestring = basestring
  40. unicode = unicode
  41. integer_types = (int, long)
  42. asbytes = str
  43. asstr = str
  44. strchar = 'S'
  45. def isfileobj(f):
  46. return isinstance(f, file)
  47. def asunicode(s):
  48. if isinstance(s, unicode):
  49. return s
  50. return str(s).decode('ascii')
  51. def open_latin1(filename, mode='r'):
  52. return open(filename, mode=mode)
  53. def sixu(s):
  54. return unicode(s, 'unicode_escape')
  55. def getexception():
  56. return sys.exc_info()[1]
  57. def asbytes_nested(x):
  58. if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
  59. return [asbytes_nested(y) for y in x]
  60. else:
  61. return asbytes(x)
  62. def asunicode_nested(x):
  63. if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
  64. return [asunicode_nested(y) for y in x]
  65. else:
  66. return asunicode(x)