py3compat.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Copyright 2009-2015 MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you
  4. # may not use this file except in compliance with the License. You
  5. # may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. # implied. See the License for the specific language governing
  13. # permissions and limitations under the License.
  14. """Utility functions and definitions for python3 compatibility."""
  15. import sys
  16. PY3 = sys.version_info[0] == 3
  17. if PY3:
  18. import codecs
  19. import _thread as thread
  20. from io import BytesIO as StringIO
  21. MAXSIZE = sys.maxsize
  22. imap = map
  23. def b(s):
  24. # BSON and socket operations deal in binary data. In
  25. # python 3 that means instances of `bytes`. In python
  26. # 2.6 and 2.7 you can create an alias for `bytes` using
  27. # the b prefix (e.g. b'foo').
  28. # See http://python3porting.com/problems.html#nicer-solutions
  29. return codecs.latin_1_encode(s)[0]
  30. def u(s):
  31. # PY3 strings may already be treated as unicode literals
  32. return s
  33. def bytes_from_hex(h):
  34. return bytes.fromhex(h)
  35. def iteritems(d):
  36. return iter(d.items())
  37. def itervalues(d):
  38. return iter(d.values())
  39. def reraise(exctype, value, trace=None):
  40. raise exctype(str(value)).with_traceback(trace)
  41. def _unicode(s):
  42. return s
  43. text_type = str
  44. string_type = str
  45. integer_types = int
  46. else:
  47. import thread
  48. from itertools import imap
  49. try:
  50. from cStringIO import StringIO
  51. except ImportError:
  52. from StringIO import StringIO
  53. MAXSIZE = sys.maxint
  54. def b(s):
  55. # See comments above. In python 2.x b('foo') is just 'foo'.
  56. return s
  57. def u(s):
  58. """Replacement for unicode literal prefix."""
  59. return unicode(s.replace('\\', '\\\\'), 'unicode_escape')
  60. def bytes_from_hex(h):
  61. return h.decode('hex')
  62. def iteritems(d):
  63. return d.iteritems()
  64. def itervalues(d):
  65. return d.itervalues()
  66. # "raise x, y, z" raises SyntaxError in Python 3
  67. exec("""def reraise(exctype, value, trace=None):
  68. raise exctype, str(value), trace
  69. """)
  70. _unicode = unicode
  71. string_type = basestring
  72. text_type = unicode
  73. integer_types = (int, long)