blob: 1cbae81d6850b2f3b287859e90c982df7153c6ff [file] [log] [blame]
Eli Bendersky3853a402012-01-26 06:51:59 +02001#-------------------------------------------------------------------------------
2# py3compat.py
3#
4# Some Python2&3 compatibility code
5#-------------------------------------------------------------------------------
6import sys
7PY3 = sys.version_info[0] == 3
8
Scott Johnson0c32a0d2019-06-22 05:16:23 -07009try:
10 from collections.abc import MutableMapping # python >= 3.3
11except ImportError:
12 from collections import MutableMapping # python < 3.3
13
Eli Bendersky3853a402012-01-26 06:51:59 +020014
15if 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
50else:
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