Debian Codegraph @

cmake/tribits/python_utils/Python2and3.py

raw
1 """
2 Python2and3: Simple set of utilities to write Python code that is Python 2 and
3 Python 3 compatible.
4 """
5
6 import sys
7
8 #
9 # Byte array / string / unicode support across Python 2 & 3
10 #
11 # Note that the str class in Python 2 is an ASCII string (byte) array and in
12 # Python 3 it is a Unicode object. For Python 3 code that is backward compatible
13 # with Python 2, we sometimes need version-specific conversion functions to give
14 # us the data type we desire. These functions are:
15 #
16 # b(x) Return a byte array of str x, much like b'<string const>' in
17 # Python 3.
18 # s(x) Return a version-specific str object equivalent to x
19 # u(x) return a unicode object equivalent to x, much like
20 # u'<string const>' in Python 2.
21 # stru() Returns the string 'u' if that would be printed in Python 2
22 # where in Python 3 return empty ''. This is used to build string
23 # representations so as generated by the str() function converting
24 # a dict to a string.
25 #
26 if sys.version_info < (3,):
27 # Python 2
28 def b(x): return x
29 def s(x): return x
30 def u(x): return unicode(x)
31 def stru(): return 'u'
32 else:
33 # Python 3
34 import codecs
35 def b(x): return codecs.latin_1_encode(x)[0]
36 def s(x):
37 try:
38 return x.decode("utf-8")
39 except AttributeError:
40 return x
41 def u(x): return x
42 def stru(): return ''
43
44
45 def csvReaderNext(csvReader):
46 if sys.version_info < (3,):
47 return csvReader.next()
48 else:
49 return next(csvReader)
50
51
52 def dictItems(dictIn):
53 if sys.version_info < (3,):
54 return dictIn.iteritems()
55 else:
56 return dictIn.items()