Debian Codegraph @

src/pygame_sdl2/compat.py

raw
1 """Python 2.x/3.x compatibility tools"""
2
3 import sys
4
5 __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_',
6 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode',
7 'file_type'
8 ]
9
10 if sys.version_info[0] >= 3:
11 import io
12 file_type = io.FileIO
13 else:
14 file_type = file
15
16 def geterror ():
17 return sys.exc_info()[1]
18
19 try:
20 long_ = long
21 except NameError:
22 long_ = int
23
24 try:
25 xrange_ = xrange
26 except NameError:
27 xrange_ = range
28
29 def get_BytesIO():
30 try:
31 from cStringIO import StringIO as BytesIO
32 except ImportError:
33 from io import BytesIO
34 return BytesIO
35
36 def get_StringIO():
37 try:
38 from cStringIO import StringIO
39 except ImportError:
40 from io import StringIO
41 return StringIO
42
43 def ord_(o):
44 try:
45 return ord(o)
46 except TypeError:
47 return o
48
49 try:
50 unichr_ = unichr
51 except NameError:
52 unichr_ = chr
53
54 try:
55 unicode_ = unicode
56 except NameError:
57 unicode_ = str
58
59 try:
60 bytes_ = bytes
61 except NameError:
62 bytes_ = str
63
64 try:
65 raw_input_ = raw_input
66 except NameError:
67 raw_input_ = input
68
69 if sys.platform == 'win32':
70 filesystem_errors = "replace"
71 elif sys.version_info >= (3, 0, 0):
72 filesystem_errors = "surrogateescape"
73 else:
74 filesystem_errors = "strict"
75
76 def filesystem_encode(u):
77 return u.encode(sys.getfilesystemencoding(), filesystem_errors)
78
79 # Represent escaped bytes and strings in a portable way.
80 #
81 # as_bytes: Allow a Python 3.x string to represent a bytes object.
82 # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3.x
83 # as_bytes("a\x01\b") == "a\x01b" # Python 2.x
84 # as_unicode: Allow a Python "r" string to represent a unicode string.
85 # e.g.: as_unicode(r"Bo\u00F6tes") == u"Bo\u00F6tes" # Python 2.x
86 # as_unicode(r"Bo\u00F6tes") == "Bo\u00F6tes" # Python 3.x
87 try:
88 unicode
89 def as_bytes(string):
90 """ '<binary literal>' => '<binary literal>' """
91 return string
92
93 def as_unicode(rstring):
94 """ r'<Unicode literal>' => u'<Unicode literal>' """
95 return rstring.decode('unicode_escape', 'strict')
96 except NameError:
97 def as_bytes(string):
98 """ '<binary literal>' => b'<binary literal>' """
99 return string.encode('latin-1', 'strict')
100
101 def as_unicode(rstring):
102 """ r'<Unicode literal>' => '<Unicode literal>' """
103 return rstring.encode('ascii', 'strict').decode('unicode_escape',
104 'stict')
105 # Include a next compatible function for Python versions < 2.6
106 try:
107 next_ = next
108 except NameError:
109 def next_(i, *args):
110 try:
111 return i.next()
112 except StopIteration:
113 if args:
114 return args[0]
115 raise
116
117 # itertools.imap is missing in 3.x
118 try:
119 import itertools.imap as imap_
120 except ImportError:
121 imap_ = map