• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Python 2/3 compat layer."""
2
3from __future__ import print_function, division, absolute_import
4
5try:
6	basestring
7except NameError:
8	basestring = str
9
10try:
11	unicode
12except NameError:
13	unicode = str
14
15try:
16	unichr
17	bytechr = chr
18	byteord = ord
19except:
20	unichr = chr
21	def bytechr(n):
22		return bytes([n])
23	def byteord(c):
24		return c if isinstance(c, int) else ord(c)
25
26try:
27	from StringIO import StringIO
28except ImportError:
29	from io import BytesIO as StringIO
30
31def strjoin(iterable):
32	return ''.join(iterable)
33if str == bytes:
34	class Tag(str):
35		def tobytes(self):
36			if isinstance(self, bytes):
37				return self
38			else:
39				return self.encode('latin1')
40
41	def tostr(s, encoding='ascii'):
42		if not isinstance(s, str):
43			return s.encode(encoding)
44		else:
45			return s
46	tobytes = tostr
47
48	bytesjoin = strjoin
49else:
50	class Tag(str):
51
52		@staticmethod
53		def transcode(blob):
54			if not isinstance(blob, str):
55				blob = blob.decode('latin-1')
56			return blob
57
58		def __new__(self, content):
59			return str.__new__(self, self.transcode(content))
60		def __ne__(self, other):
61			return not self.__eq__(other)
62		def __eq__(self, other):
63			return str.__eq__(self, self.transcode(other))
64
65		def __hash__(self):
66			return str.__hash__(self)
67
68		def tobytes(self):
69			return self.encode('latin-1')
70
71	def tostr(s, encoding='ascii'):
72		if not isinstance(s, str):
73			return s.decode(encoding)
74		else:
75			return s
76	def tobytes(s, encoding='ascii'):
77		if not isinstance(s, bytes):
78			return s.encode(encoding)
79		else:
80			return s
81
82	def bytesjoin(iterable):
83		return b''.join(tobytes(item) for item in iterable)
84