_compat.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import sys
  2. import array
  3. PY2 = sys.version_info[0] == 2
  4. _identity = lambda x: x
  5. if not PY2:
  6. text_type = str
  7. string_types = (str,)
  8. integer_types = (int, )
  9. text_to_native = lambda s, enc: s
  10. unichr = chr
  11. iterkeys = lambda d: iter(d.keys())
  12. itervalues = lambda d: iter(d.values())
  13. iteritems = lambda d: iter(d.items())
  14. from io import StringIO, BytesIO
  15. import pickle
  16. izip = zip
  17. imap = map
  18. range_type = range
  19. cmp = lambda a, b: (a > b) - (a < b)
  20. array_tobytes = array.array.tobytes
  21. from collections import abc
  22. else:
  23. text_type = unicode
  24. string_types = (str, unicode)
  25. integer_types = (int, long)
  26. text_to_native = lambda s, enc: s.encode(enc)
  27. unichr = unichr
  28. iterkeys = lambda d: d.iterkeys()
  29. itervalues = lambda d: d.itervalues()
  30. iteritems = lambda d: d.iteritems()
  31. from cStringIO import StringIO as BytesIO
  32. from StringIO import StringIO
  33. import cPickle as pickle
  34. from itertools import imap
  35. from itertools import izip
  36. range_type = xrange
  37. cmp = cmp
  38. array_tobytes = array.array.tostring
  39. import collections as abc
  40. number_types = integer_types + (float,)
  41. def force_text(s, encoding='utf-8', errors='strict'):
  42. if isinstance(s, text_type):
  43. return s
  44. if isinstance(s, bytes):
  45. return s.decode(encoding, errors)
  46. return text_type(s)
  47. #
  48. # Since Python 3.3, a fast decimal implementation is already included in the
  49. # standard library. Otherwise use cdecimal when available
  50. #
  51. if sys.version_info[:2] >= (3, 3):
  52. import decimal
  53. else:
  54. try:
  55. import cdecimal as decimal
  56. except ImportError:
  57. import decimal