Eli Bendersky | 3853a40 | 2012-01-26 06:51:59 +0200 | [diff] [blame] | 1 | #------------------------------------------------------------------------------- |
| 2 | # py3compat.py |
| 3 | # |
| 4 | # Some Python2&3 compatibility code |
| 5 | #------------------------------------------------------------------------------- |
| 6 | import sys |
| 7 | PY3 = sys.version_info[0] == 3 |
| 8 | |
Scott Johnson | 0c32a0d | 2019-06-22 05:16:23 -0700 | [diff] [blame^] | 9 | try: |
| 10 | from collections.abc import MutableMapping # python >= 3.3 |
| 11 | except ImportError: |
| 12 | from collections import MutableMapping # python < 3.3 |
| 13 | |
Eli Bendersky | 3853a40 | 2012-01-26 06:51:59 +0200 | [diff] [blame] | 14 | |
| 15 | if PY3: |
| 16 | import io |
| 17 | StringIO = io.StringIO |
| 18 | BytesIO = io.BytesIO |
| 19 | |
| 20 | def bchr(i): |
| 21 | """ When iterating over b'...' in Python 2 you get single b'_' chars |
| 22 | and in Python 3 you get integers. Call bchr to always turn this |
| 23 | to single b'_' chars. |
| 24 | """ |
| 25 | return bytes((i,)) |
| 26 | |
| 27 | def u(s): |
| 28 | return s |
| 29 | |
| 30 | def int2byte(i): |
| 31 | return bytes((i,)) |
| 32 | |
| 33 | def byte2int(b): |
| 34 | return b |
| 35 | |
| 36 | def str2bytes(s): |
| 37 | return s.encode("latin-1") |
| 38 | |
| 39 | def str2unicode(s): |
| 40 | return s |
| 41 | |
| 42 | def bytes2str(b): |
| 43 | return b.decode('latin-1') |
| 44 | |
| 45 | def decodebytes(b, encoding): |
| 46 | return bytes(b, encoding) |
| 47 | |
| 48 | advance_iterator = next |
| 49 | |
| 50 | else: |
| 51 | import cStringIO |
| 52 | StringIO = BytesIO = cStringIO.StringIO |
| 53 | |
| 54 | int2byte = chr |
| 55 | byte2int = ord |
| 56 | bchr = lambda i: i |
| 57 | |
| 58 | def u(s): |
| 59 | return unicode(s, "unicode_escape") |
| 60 | |
| 61 | def str2bytes(s): |
| 62 | return s |
| 63 | |
| 64 | def str2unicode(s): |
| 65 | return unicode(s, "unicode_escape") |
| 66 | |
| 67 | def bytes2str(b): |
| 68 | return b |
| 69 | |
| 70 | def decodebytes(b, encoding): |
| 71 | return b.decode(encoding) |
| 72 | |
| 73 | def advance_iterator(it): |
| 74 | return it.next() |
| 75 | |