##// END OF EJS Templates
remove unnecessary function call
Brandon Parsons -
Show More
@@ -1,207 +1,207 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 import __builtin__
3 import __builtin__
4 import functools
4 import functools
5 import sys
5 import sys
6 import re
6 import re
7 import types
7 import types
8 import locale
8 import locale
9
9
10 orig_open = open
10 orig_open = open
11
11
12 def no_code(x, encoding=None):
12 def no_code(x, encoding=None):
13 return x
13 return x
14
14
15 # to deal with the possibility of sys.std* not being a stream at all
15 # to deal with the possibility of sys.std* not being a stream at all
16 def get_stream_enc(stream, default=None):
16 def get_stream_enc(stream, default=None):
17 if not hasattr(stream, 'encoding') or not stream.encoding:
17 if not hasattr(stream, 'encoding') or not stream.encoding:
18 return default
18 return default
19 else:
19 else:
20 return stream.encoding
20 return stream.encoding
21
21
22 # Less conservative replacement for sys.getdefaultencoding, that will try
22 # Less conservative replacement for sys.getdefaultencoding, that will try
23 # to match the environment.
23 # to match the environment.
24 # Defined here as central function, so if we find better choices, we
24 # Defined here as central function, so if we find better choices, we
25 # won't need to make changes all over IPython.
25 # won't need to make changes all over IPython.
26 def getdefaultencoding():
26 def getdefaultencoding():
27 """Return IPython's guess for the default encoding for bytes as text.
27 """Return IPython's guess for the default encoding for bytes as text.
28
28
29 Asks for stdin.encoding first, to match the calling Terminal, but that
29 Asks for stdin.encoding first, to match the calling Terminal, but that
30 is often None for subprocesses. Fall back on locale.getpreferredencoding()
30 is often None for subprocesses. Fall back on locale.getpreferredencoding()
31 which should be a sensible platform default (that respects LANG environment),
31 which should be a sensible platform default (that respects LANG environment),
32 and finally to sys.getdefaultencoding() which is the most conservative option,
32 and finally to sys.getdefaultencoding() which is the most conservative option,
33 and usually ASCII.
33 and usually ASCII.
34 """
34 """
35 enc = get_stream_enc(sys.stdin)
35 enc = get_stream_enc(sys.stdin)
36 if not enc or enc=='ascii':
36 if not enc or enc=='ascii':
37 try:
37 try:
38 # There are reports of getpreferredencoding raising errors
38 # There are reports of getpreferredencoding raising errors
39 # in some cases, which may well be fixed, but let's be conservative here.
39 # in some cases, which may well be fixed, but let's be conservative here.
40 enc = locale.getpreferredencoding()
40 enc = locale.getpreferredencoding()
41 except Exception:
41 except Exception:
42 pass
42 pass
43 return enc or sys.getdefaultencoding()
43 return enc or sys.getdefaultencoding()
44
44
45 def decode(s, encoding=None):
45 def decode(s, encoding=None):
46 encoding = get_stream_enc(sys.stdin, encoding) or getdefaultencoding()
46 encoding = encoding or getdefaultencoding()
47 return s.decode(encoding, "replace")
47 return s.decode(encoding, "replace")
48
48
49 def encode(u, encoding=None):
49 def encode(u, encoding=None):
50 encoding = get_stream_enc(sys.stdin, encoding) or getdefaultencoding()
50 encoding = encoding or getdefaultencoding()
51 return u.encode(encoding, "replace")
51 return u.encode(encoding, "replace")
52
52
53
53
54 def cast_unicode(s, encoding=None):
54 def cast_unicode(s, encoding=None):
55 if isinstance(s, bytes):
55 if isinstance(s, bytes):
56 return decode(s, encoding)
56 return decode(s, encoding)
57 return s
57 return s
58
58
59 def cast_bytes(s, encoding=None):
59 def cast_bytes(s, encoding=None):
60 if not isinstance(s, bytes):
60 if not isinstance(s, bytes):
61 return encode(s, encoding)
61 return encode(s, encoding)
62 return s
62 return s
63
63
64 def _modify_str_or_docstring(str_change_func):
64 def _modify_str_or_docstring(str_change_func):
65 @functools.wraps(str_change_func)
65 @functools.wraps(str_change_func)
66 def wrapper(func_or_str):
66 def wrapper(func_or_str):
67 if isinstance(func_or_str, basestring):
67 if isinstance(func_or_str, basestring):
68 func = None
68 func = None
69 doc = func_or_str
69 doc = func_or_str
70 else:
70 else:
71 func = func_or_str
71 func = func_or_str
72 doc = func.__doc__
72 doc = func.__doc__
73
73
74 doc = str_change_func(doc)
74 doc = str_change_func(doc)
75
75
76 if func:
76 if func:
77 func.__doc__ = doc
77 func.__doc__ = doc
78 return func
78 return func
79 return doc
79 return doc
80 return wrapper
80 return wrapper
81
81
82 if sys.version_info[0] >= 3:
82 if sys.version_info[0] >= 3:
83 PY3 = True
83 PY3 = True
84
84
85 input = input
85 input = input
86 builtin_mod_name = "builtins"
86 builtin_mod_name = "builtins"
87
87
88 str_to_unicode = no_code
88 str_to_unicode = no_code
89 unicode_to_str = no_code
89 unicode_to_str = no_code
90 str_to_bytes = encode
90 str_to_bytes = encode
91 bytes_to_str = decode
91 bytes_to_str = decode
92 cast_bytes_py2 = no_code
92 cast_bytes_py2 = no_code
93
93
94 def isidentifier(s, dotted=False):
94 def isidentifier(s, dotted=False):
95 if dotted:
95 if dotted:
96 return all(isidentifier(a) for a in s.split("."))
96 return all(isidentifier(a) for a in s.split("."))
97 return s.isidentifier()
97 return s.isidentifier()
98
98
99 open = orig_open
99 open = orig_open
100
100
101 MethodType = types.MethodType
101 MethodType = types.MethodType
102
102
103 def execfile(fname, glob, loc=None):
103 def execfile(fname, glob, loc=None):
104 loc = loc if (loc is not None) else glob
104 loc = loc if (loc is not None) else glob
105 exec compile(open(fname, 'rb').read(), fname, 'exec') in glob, loc
105 exec compile(open(fname, 'rb').read(), fname, 'exec') in glob, loc
106
106
107 # Refactor print statements in doctests.
107 # Refactor print statements in doctests.
108 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
108 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
109 def _print_statement_sub(match):
109 def _print_statement_sub(match):
110 expr = match.groups('expr')
110 expr = match.groups('expr')
111 return "print(%s)" % expr
111 return "print(%s)" % expr
112
112
113 @_modify_str_or_docstring
113 @_modify_str_or_docstring
114 def doctest_refactor_print(doc):
114 def doctest_refactor_print(doc):
115 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
115 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
116 unfortunately doesn't pick up on our doctests.
116 unfortunately doesn't pick up on our doctests.
117
117
118 Can accept a string or a function, so it can be used as a decorator."""
118 Can accept a string or a function, so it can be used as a decorator."""
119 return _print_statement_re.sub(_print_statement_sub, doc)
119 return _print_statement_re.sub(_print_statement_sub, doc)
120
120
121 # Abstract u'abc' syntax:
121 # Abstract u'abc' syntax:
122 @_modify_str_or_docstring
122 @_modify_str_or_docstring
123 def u_format(s):
123 def u_format(s):
124 """"{u}'abc'" --> "'abc'" (Python 3)
124 """"{u}'abc'" --> "'abc'" (Python 3)
125
125
126 Accepts a string or a function, so it can be used as a decorator."""
126 Accepts a string or a function, so it can be used as a decorator."""
127 return s.format(u='')
127 return s.format(u='')
128
128
129 else:
129 else:
130 PY3 = False
130 PY3 = False
131
131
132 input = raw_input
132 input = raw_input
133 builtin_mod_name = "__builtin__"
133 builtin_mod_name = "__builtin__"
134
134
135 str_to_unicode = decode
135 str_to_unicode = decode
136 unicode_to_str = encode
136 unicode_to_str = encode
137 str_to_bytes = no_code
137 str_to_bytes = no_code
138 bytes_to_str = no_code
138 bytes_to_str = no_code
139 cast_bytes_py2 = cast_bytes
139 cast_bytes_py2 = cast_bytes
140
140
141 import re
141 import re
142 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
142 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
143 def isidentifier(s, dotted=False):
143 def isidentifier(s, dotted=False):
144 if dotted:
144 if dotted:
145 return all(isidentifier(a) for a in s.split("."))
145 return all(isidentifier(a) for a in s.split("."))
146 return bool(_name_re.match(s))
146 return bool(_name_re.match(s))
147
147
148 class open(object):
148 class open(object):
149 """Wrapper providing key part of Python 3 open() interface."""
149 """Wrapper providing key part of Python 3 open() interface."""
150 def __init__(self, fname, mode="r", encoding="utf-8"):
150 def __init__(self, fname, mode="r", encoding="utf-8"):
151 self.f = orig_open(fname, mode)
151 self.f = orig_open(fname, mode)
152 self.enc = encoding
152 self.enc = encoding
153
153
154 def write(self, s):
154 def write(self, s):
155 return self.f.write(s.encode(self.enc))
155 return self.f.write(s.encode(self.enc))
156
156
157 def read(self, size=-1):
157 def read(self, size=-1):
158 return self.f.read(size).decode(self.enc)
158 return self.f.read(size).decode(self.enc)
159
159
160 def close(self):
160 def close(self):
161 return self.f.close()
161 return self.f.close()
162
162
163 def __enter__(self):
163 def __enter__(self):
164 return self
164 return self
165
165
166 def __exit__(self, etype, value, traceback):
166 def __exit__(self, etype, value, traceback):
167 self.f.close()
167 self.f.close()
168
168
169 def MethodType(func, instance):
169 def MethodType(func, instance):
170 return types.MethodType(func, instance, type(instance))
170 return types.MethodType(func, instance, type(instance))
171
171
172 # don't override system execfile on 2.x:
172 # don't override system execfile on 2.x:
173 execfile = execfile
173 execfile = execfile
174
174
175 def doctest_refactor_print(func_or_str):
175 def doctest_refactor_print(func_or_str):
176 return func_or_str
176 return func_or_str
177
177
178
178
179 # Abstract u'abc' syntax:
179 # Abstract u'abc' syntax:
180 @_modify_str_or_docstring
180 @_modify_str_or_docstring
181 def u_format(s):
181 def u_format(s):
182 """"{u}'abc'" --> "u'abc'" (Python 2)
182 """"{u}'abc'" --> "u'abc'" (Python 2)
183
183
184 Accepts a string or a function, so it can be used as a decorator."""
184 Accepts a string or a function, so it can be used as a decorator."""
185 return s.format(u='u')
185 return s.format(u='u')
186
186
187 if sys.platform == 'win32':
187 if sys.platform == 'win32':
188 def execfile(fname, glob=None, loc=None):
188 def execfile(fname, glob=None, loc=None):
189 loc = loc if (loc is not None) else glob
189 loc = loc if (loc is not None) else glob
190 # The rstrip() is necessary b/c trailing whitespace in files will
190 # The rstrip() is necessary b/c trailing whitespace in files will
191 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
191 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
192 # but we still support 2.6). See issue 1027.
192 # but we still support 2.6). See issue 1027.
193 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
193 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
194 # compile converts unicode filename to str assuming
194 # compile converts unicode filename to str assuming
195 # ascii. Let's do the conversion before calling compile
195 # ascii. Let's do the conversion before calling compile
196 if isinstance(fname, unicode):
196 if isinstance(fname, unicode):
197 filename = unicode_to_str(fname)
197 filename = unicode_to_str(fname)
198 else:
198 else:
199 filename = fname
199 filename = fname
200 exec compile(scripttext, filename, 'exec') in glob, loc
200 exec compile(scripttext, filename, 'exec') in glob, loc
201 else:
201 else:
202 def execfile(fname, *where):
202 def execfile(fname, *where):
203 if isinstance(fname, unicode):
203 if isinstance(fname, unicode):
204 filename = fname.encode(sys.getfilesystemencoding())
204 filename = fname.encode(sys.getfilesystemencoding())
205 else:
205 else:
206 filename = fname
206 filename = fname
207 __builtin__.execfile(filename, *where)
207 __builtin__.execfile(filename, *where)
General Comments 0
You need to be logged in to leave comments. Login now