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 | |
| 9 | |
| 10 | if PY3: |
| 11 | import io |
| 12 | StringIO = io.StringIO |
| 13 | BytesIO = io.BytesIO |
| 14 | |
| 15 | def bchr(i): |
| 16 | """ When iterating over b'...' in Python 2 you get single b'_' chars |
| 17 | and in Python 3 you get integers. Call bchr to always turn this |
| 18 | to single b'_' chars. |
| 19 | """ |
| 20 | return bytes((i,)) |
| 21 | |
| 22 | def u(s): |
| 23 | return s |
| 24 | |
| 25 | def int2byte(i): |
| 26 | return bytes((i,)) |
| 27 | |
| 28 | def byte2int(b): |
| 29 | return b |
| 30 | |
| 31 | def str2bytes(s): |
| 32 | return s.encode("latin-1") |
| 33 | |
| 34 | def str2unicode(s): |
| 35 | return s |
| 36 | |
| 37 | def bytes2str(b): |
| 38 | return b.decode('latin-1') |
| 39 | |
| 40 | def decodebytes(b, encoding): |
| 41 | return bytes(b, encoding) |
| 42 | |
| 43 | advance_iterator = next |
| 44 | |
| 45 | else: |
| 46 | import cStringIO |
| 47 | StringIO = BytesIO = cStringIO.StringIO |
| 48 | |
| 49 | int2byte = chr |
| 50 | byte2int = ord |
| 51 | bchr = lambda i: i |
| 52 | |
| 53 | def u(s): |
| 54 | return unicode(s, "unicode_escape") |
| 55 | |
| 56 | def str2bytes(s): |
| 57 | return s |
| 58 | |
| 59 | def str2unicode(s): |
| 60 | return unicode(s, "unicode_escape") |
| 61 | |
| 62 | def bytes2str(b): |
| 63 | return b |
| 64 | |
| 65 | def decodebytes(b, encoding): |
| 66 | return b.decode(encoding) |
| 67 | |
| 68 | def advance_iterator(it): |
| 69 | return it.next() |
| 70 | |