##// END OF EJS Templates
Remove redundant Python 2 code
Hugo -
r24010:77b36a9f
parent child
Show More
Add another comment
@@ -21,5 +21,6 __pycache__
21 .DS_Store
21 .DS_Store
22 \#*#
22 \#*#
23 .#*
23 .#*
24 .cache
24 .coverage
25 .coverage
25 *.swp
26 *.swp
@@ -218,8 +218,8 class ScriptMagics(Magics):
218 print("Error while terminating subprocess (pid=%i): %s" \
218 print("Error while terminating subprocess (pid=%i): %s" \
219 % (p.pid, e))
219 % (p.pid, e))
220 return
220 return
221 out = py3compat.bytes_to_str(out)
221 out = py3compat.decode(out)
222 err = py3compat.bytes_to_str(err)
222 err = py3compat.decode(err)
223 if args.out:
223 if args.out:
224 self.shell.user_ns[args.out] = out
224 self.shell.user_ns[args.out] = out
225 else:
225 else:
@@ -10,7 +10,6 from traitlets import Unicode
10
10
11 from IPython.core.application import BaseIPythonApplication
11 from IPython.core.application import BaseIPythonApplication
12 from IPython.testing import decorators as dec
12 from IPython.testing import decorators as dec
13 from IPython.utils import py3compat
14 from IPython.utils.tempdir import TemporaryDirectory
13 from IPython.utils.tempdir import TemporaryDirectory
15
14
16
15
@@ -22,7 +22,6 import nose.tools as nt
22
22
23 # Our own imports
23 # Our own imports
24 from IPython.core import compilerop
24 from IPython.core import compilerop
25 from IPython.utils import py3compat
26
25
27 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
28 # Test functions
27 # Test functions
@@ -17,7 +17,6 from os.path import join
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.core.completerlib import magic_run_completer, module_completion
19 from IPython.core.completerlib import magic_run_completer, module_completion
20 from IPython.utils import py3compat
21 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.tempdir import TemporaryDirectory
22 from IPython.testing.decorators import onlyif_unicode_paths
21 from IPython.testing.decorators import onlyif_unicode_paths
23
22
@@ -19,7 +19,6 import nose.tools as nt
19 from traitlets.config.loader import Config
19 from traitlets.config.loader import Config
20 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.tempdir import TemporaryDirectory
21 from IPython.core.history import HistoryManager, extract_hist_ranges
21 from IPython.core.history import HistoryManager, extract_hist_ranges
22 from IPython.utils import py3compat
23
22
24 def setUp():
23 def setUp():
25 nt.assert_equal(sys.getdefaultencoding(), "utf-8")
24 nt.assert_equal(sys.getdefaultencoding(), "utf-8")
@@ -17,7 +17,6 import sys
17 import tempfile
17 import tempfile
18 import unittest
18 import unittest
19 from unittest import mock
19 from unittest import mock
20 from io import StringIO
21
20
22 from os.path import join
21 from os.path import join
23
22
@@ -30,7 +29,6 from IPython.testing.decorators import (
30 )
29 )
31 from IPython.testing import tools as tt
30 from IPython.testing import tools as tt
32 from IPython.utils.process import find_cmd
31 from IPython.utils.process import find_cmd
33 from IPython.utils import py3compat
34
32
35 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
36 # Globals
34 # Globals
@@ -19,10 +19,8 from IPython.core.magic import (Magics, magics_class, line_magic,
19 register_line_cell_magic)
19 register_line_cell_magic)
20 from decorator import decorator
20 from decorator import decorator
21 from IPython import get_ipython
21 from IPython import get_ipython
22 from IPython.testing.decorators import skipif
23 from IPython.testing.tools import AssertPrints, AssertNotPrints
22 from IPython.testing.tools import AssertPrints, AssertNotPrints
24 from IPython.utils.path import compress_user
23 from IPython.utils.path import compress_user
25 from IPython.utils import py3compat
26
24
27
25
28 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
@@ -40,14 +38,14 ip = get_ipython()
40 # defined, if any code is inserted above, the following line will need to be
38 # defined, if any code is inserted above, the following line will need to be
41 # updated. Do NOT insert any whitespace between the next line and the function
39 # updated. Do NOT insert any whitespace between the next line and the function
42 # definition below.
40 # definition below.
43 THIS_LINE_NUMBER = 43 # Put here the actual number of this line
41 THIS_LINE_NUMBER = 41 # Put here the actual number of this line
44
42
45 from unittest import TestCase
43 from unittest import TestCase
46
44
47 class Test(TestCase):
45 class Test(TestCase):
48
46
49 def test_find_source_lines(self):
47 def test_find_source_lines(self):
50 self.assertEqual(oinspect.find_source_lines(Test.test_find_source_lines),
48 self.assertEqual(oinspect.find_source_lines(Test.test_find_source_lines),
51 THIS_LINE_NUMBER+6)
49 THIS_LINE_NUMBER+6)
52
50
53
51
@@ -3,7 +3,6 import nose.tools as nt
3
3
4 from IPython.core.splitinput import split_user_input, LineInfo
4 from IPython.core.splitinput import split_user_input, LineInfo
5 from IPython.testing import tools as tt
5 from IPython.testing import tools as tt
6 from IPython.utils import py3compat
7
6
8 tests = [
7 tests = [
9 ('x=1', ('', '', 'x', '=1')),
8 ('x=1', ('', '', 'x', '=1')),
@@ -1136,35 +1136,32 class VerboseTB(TBTools):
1136 colorsnormal = colors.Normal # used a lot
1136 colorsnormal = colors.Normal # used a lot
1137 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1137 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1138 structured_traceback_parts = [head]
1138 structured_traceback_parts = [head]
1139 if py3compat.PY3:
1139 chained_exceptions_tb_offset = 0
1140 chained_exceptions_tb_offset = 0
1140 lines_of_context = 3
1141 lines_of_context = 3
1141 formatted_exceptions = formatted_exception
1142 formatted_exceptions = formatted_exception
1142 exception = self.get_parts_of_chained_exception(evalue)
1143 if exception:
1144 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1145 etype, evalue, etb = exception
1146 else:
1147 evalue = None
1148 chained_exc_ids = set()
1149 while evalue:
1150 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1151 chained_exceptions_tb_offset)
1143 exception = self.get_parts_of_chained_exception(evalue)
1152 exception = self.get_parts_of_chained_exception(evalue)
1144 if exception:
1153
1154 if exception and not id(exception[1]) in chained_exc_ids:
1155 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1145 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1156 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1146 etype, evalue, etb = exception
1157 etype, evalue, etb = exception
1147 else:
1158 else:
1148 evalue = None
1159 evalue = None
1149 chained_exc_ids = set()
1150 while evalue:
1151 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1152 chained_exceptions_tb_offset)
1153 exception = self.get_parts_of_chained_exception(evalue)
1154
1155 if exception and not id(exception[1]) in chained_exc_ids:
1156 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1157 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1158 etype, evalue, etb = exception
1159 else:
1160 evalue = None
1161
1160
1162 # we want to see exceptions in a reversed order:
1161 # we want to see exceptions in a reversed order:
1163 # the first exception should be on top
1162 # the first exception should be on top
1164 for formatted_exception in reversed(formatted_exceptions):
1163 for formatted_exception in reversed(formatted_exceptions):
1165 structured_traceback_parts += formatted_exception
1164 structured_traceback_parts += formatted_exception
1166 else:
1167 structured_traceback_parts += formatted_exception[0]
1168
1165
1169 return structured_traceback_parts
1166 return structured_traceback_parts
1170
1167
@@ -116,7 +116,6 import traceback
116 import types
116 import types
117 import weakref
117 import weakref
118 from importlib import import_module
118 from importlib import import_module
119 from IPython.utils.py3compat import PY3
120 from imp import reload
119 from imp import reload
121
120
122 from IPython.utils import openpy
121 from IPython.utils import openpy
@@ -11,7 +11,7 import random
11
11
12 # Our own
12 # Our own
13 from IPython.core.error import UsageError
13 from IPython.core.error import UsageError
14 from IPython.utils.py3compat import cast_bytes, str_to_bytes
14 from IPython.utils.py3compat import encode
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Globals
17 # Globals
@@ -65,7 +65,7 def passwd(passphrase=None, algorithm='sha1'):
65
65
66 h = hashlib.new(algorithm)
66 h = hashlib.new(algorithm)
67 salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
67 salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
68 h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))
68 h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii'))
69
69
70 return ':'.join((algorithm, salt, h.hexdigest()))
70 return ':'.join((algorithm, salt, h.hexdigest()))
71
71
@@ -109,6 +109,6 def passwd_check(hashed_passphrase, passphrase):
109 if len(pw_digest) == 0:
109 if len(pw_digest) == 0:
110 return False
110 return False
111
111
112 h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii'))
112 h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii'))
113
113
114 return h.hexdigest() == pw_digest
114 return h.hexdigest() == pw_digest
@@ -7,7 +7,7 from warnings import warn
7
7
8 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
8 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.utils import io
9 from IPython.utils import io
10 from IPython.utils.py3compat import input, cast_unicode_py2
10 from IPython.utils.py3compat import input
11 from IPython.utils.terminal import toggle_set_term_title, set_term_title
11 from IPython.utils.terminal import toggle_set_term_title, set_term_title
12 from IPython.utils.process import abbrev_cwd
12 from IPython.utils.process import abbrev_cwd
13 from traitlets import (
13 from traitlets import (
@@ -233,7 +233,7 class TerminalInteractiveShell(InteractiveShell):
233 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
233 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
234 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
234 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
235 while isp.push_accepts_more():
235 while isp.push_accepts_more():
236 line = cast_unicode_py2(input(prompt_text))
236 line = input(prompt_text)
237 isp.push(line)
237 isp.push(line)
238 prompt_text = prompt_continuation
238 prompt_text = prompt_continuation
239 return isp.source_reset()
239 return isp.source_reset()
@@ -31,8 +31,9 we've copied verbatim from numpy.
31 # Copyright (c) IPython Development Team.
31 # Copyright (c) IPython Development Team.
32 # Distributed under the terms of the Modified BSD License.
32 # Distributed under the terms of the Modified BSD License.
33
33
34 import sys
35 import os
34 import os
35 import shutil
36 import sys
36 import tempfile
37 import tempfile
37 import unittest
38 import unittest
38 import warnings
39 import warnings
@@ -48,9 +49,6 from .ipunittest import ipdoctest, ipdocstring
48 # numpy.testing.decorators, we expose all of it here.
49 # numpy.testing.decorators, we expose all of it here.
49 from IPython.external.decorators import *
50 from IPython.external.decorators import *
50
51
51 # For onlyif_cmd_exists decorator
52 from IPython.utils.py3compat import which
53
54 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
55 # Classes and functions
53 # Classes and functions
56 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
@@ -360,7 +358,7 def onlyif_cmds_exist(*commands):
360 Decorator to skip test when at least one of `commands` is not found.
358 Decorator to skip test when at least one of `commands` is not found.
361 """
359 """
362 for cmd in commands:
360 for cmd in commands:
363 if not which(cmd):
361 if not shutil.which(cmd):
364 return skip("This test runs only if command '{0}' "
362 return skip("This test runs only if command '{0}' "
365 "is installed".format(cmd))
363 "is installed".format(cmd))
366 return null_deco
364 return null_deco
@@ -372,7 +370,7 def onlyif_any_cmd_exists(*commands):
372 warnings.warn("The function `onlyif_any_cmd_exists` is deprecated since IPython 4.0",
370 warnings.warn("The function `onlyif_any_cmd_exists` is deprecated since IPython 4.0",
373 DeprecationWarning, stacklevel=2)
371 DeprecationWarning, stacklevel=2)
374 for cmd in commands:
372 for cmd in commands:
375 if which(cmd):
373 if shutil.which(cmd):
376 return null_deco
374 return null_deco
377 return skip("This test runs only if one of the commands {0} "
375 return skip("This test runs only if one of the commands {0} "
378 "is installed".format(commands))
376 "is installed".format(commands))
@@ -11,13 +11,13 done.
11
11
12 import builtins as builtin_mod
12 import builtins as builtin_mod
13 import sys
13 import sys
14 import types
14 import warnings
15 import warnings
15
16
16 from . import tools
17 from . import tools
17
18
18 from IPython.core import page
19 from IPython.core import page
19 from IPython.utils import io
20 from IPython.utils import io
20 from IPython.utils import py3compat
21 from IPython.terminal.interactiveshell import TerminalInteractiveShell
21 from IPython.terminal.interactiveshell import TerminalInteractiveShell
22
22
23
23
@@ -104,9 +104,9 def start_ipython():
104 # Modify the IPython system call with one that uses getoutput, so that we
104 # Modify the IPython system call with one that uses getoutput, so that we
105 # can capture subcommands and print them to Python's stdout, otherwise the
105 # can capture subcommands and print them to Python's stdout, otherwise the
106 # doctest machinery would miss them.
106 # doctest machinery would miss them.
107 shell.system = py3compat.MethodType(xsys, shell)
107 shell.system = types.MethodType(xsys, shell)
108
108
109 shell._showtraceback = py3compat.MethodType(_showtraceback, shell)
109 shell._showtraceback = types.MethodType(_showtraceback, shell)
110
110
111 # IPython is ready, now clean up some global state...
111 # IPython is ready, now clean up some global state...
112
112
@@ -34,7 +34,7 from nose.plugins import Plugin
34 from nose.util import safe_str
34 from nose.util import safe_str
35
35
36 from IPython import version_info
36 from IPython import version_info
37 from IPython.utils.py3compat import bytes_to_str
37 from IPython.utils.py3compat import decode
38 from IPython.utils.importstring import import_item
38 from IPython.utils.importstring import import_item
39 from IPython.testing.plugin.ipdoctest import IPythonDoctest
39 from IPython.testing.plugin.ipdoctest import IPythonDoctest
40 from IPython.external.decorators import KnownFailure, knownfailureif
40 from IPython.external.decorators import KnownFailure, knownfailureif
@@ -299,8 +299,8 class StreamCapturer(Thread):
299 with self.buffer_lock:
299 with self.buffer_lock:
300 self.buffer.write(chunk)
300 self.buffer.write(chunk)
301 if self.echo:
301 if self.echo:
302 sys.stdout.write(bytes_to_str(chunk))
302 sys.stdout.write(decode(chunk))
303
303
304 os.close(self.readfd)
304 os.close(self.readfd)
305 os.close(self.writefd)
305 os.close(self.writefd)
306
306
@@ -24,7 +24,7 from .iptest import (
24 have, test_group_names as py_test_group_names, test_sections, StreamCapturer,
24 have, test_group_names as py_test_group_names, test_sections, StreamCapturer,
25 )
25 )
26 from IPython.utils.path import compress_user
26 from IPython.utils.path import compress_user
27 from IPython.utils.py3compat import bytes_to_str
27 from IPython.utils.py3compat import decode
28 from IPython.utils.sysinfo import get_sys_info
28 from IPython.utils.sysinfo import get_sys_info
29 from IPython.utils.tempdir import TemporaryDirectory
29 from IPython.utils.tempdir import TemporaryDirectory
30
30
@@ -371,7 +371,7 def run_iptestall(options):
371 print(justify('Test group: ' + controller.section, res_string))
371 print(justify('Test group: ' + controller.section, res_string))
372 if res:
372 if res:
373 controller.print_extra_info()
373 controller.print_extra_info()
374 print(bytes_to_str(controller.stdout))
374 print(decode(controller.stdout))
375 failed.append(controller)
375 failed.append(controller)
376 if res == -signal.SIGINT:
376 if res == -signal.SIGINT:
377 print("Interrupted")
377 print("Interrupted")
@@ -33,7 +33,6 from IPython.utils.process import get_output_error_code
33 from IPython.utils.text import list_strings
33 from IPython.utils.text import list_strings
34 from IPython.utils.io import temp_pyfile, Tee
34 from IPython.utils.io import temp_pyfile, Tee
35 from IPython.utils import py3compat
35 from IPython.utils import py3compat
36 from IPython.utils.encoding import DEFAULT_ENCODING
37
36
38 from . import decorators as dec
37 from . import decorators as dec
39 from . import skipdoctest
38 from . import skipdoctest
@@ -210,8 +209,8 def ipexec(fname, options=None, commands=()):
210 if not isinstance(v, str):
209 if not isinstance(v, str):
211 print(k, v)
210 print(k, v)
212 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
211 p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
213 out, err = p.communicate(input=py3compat.str_to_bytes('\n'.join(commands)) or None)
212 out, err = p.communicate(input=py3compat.encode('\n'.join(commands)) or None)
214 out, err = py3compat.bytes_to_str(out), py3compat.bytes_to_str(err)
213 out, err = py3compat.decode(out), py3compat.decode(err)
215 # `import readline` causes 'ESC[?1034h' to be output sometimes,
214 # `import readline` causes 'ESC[?1034h' to be output sometimes,
216 # so strip that out before doing comparisons
215 # so strip that out before doing comparisons
217 if out:
216 if out:
@@ -28,7 +28,7 def _find_cmd(cmd):
28 for path in paths:
28 for path in paths:
29 filename = os.path.join(path, cmd)
29 filename = os.path.join(path, cmd)
30 if System.IO.File.Exists(filename):
30 if System.IO.File.Exists(filename):
31 return py3compat.bytes_to_str(filename)
31 return py3compat.decode(filename)
32 raise OSError("command %r not found" % cmd)
32 raise OSError("command %r not found" % cmd)
33
33
34 def system(cmd):
34 def system(cmd):
@@ -130,7 +130,7 def getoutput(cmd):
130 out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
130 out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
131 if out is None:
131 if out is None:
132 return ''
132 return ''
133 return py3compat.bytes_to_str(out)
133 return py3compat.decode(out)
134
134
135
135
136 def getoutputerror(cmd):
136 def getoutputerror(cmd):
@@ -172,7 +172,7 def get_output_error_code(cmd):
172 if out_err is None:
172 if out_err is None:
173 return '', '', p.returncode
173 return '', '', p.returncode
174 out, err = out_err
174 out, err = out_err
175 return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err), p.returncode
175 return py3compat.decode(out), py3compat.decode(err), p.returncode
176
176
177 def arg_split(s, posix=False, strict=True):
177 def arg_split(s, posix=False, strict=True):
178 """Split a command line's arguments in a shell-like manner.
178 """Split a command line's arguments in a shell-like manner.
@@ -36,7 +36,7 def _find_cmd(cmd):
36
36
37 path = sp.Popen(['/usr/bin/env', 'which', cmd],
37 path = sp.Popen(['/usr/bin/env', 'which', cmd],
38 stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]
38 stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0]
39 return py3compat.bytes_to_str(path)
39 return py3compat.decode(path)
40
40
41
41
42 class ProcessHandler(object):
42 class ProcessHandler(object):
@@ -152,7 +152,7 def getoutput(cmd):
152
152
153 if out is None:
153 if out is None:
154 out = b''
154 out = b''
155 return py3compat.bytes_to_str(out)
155 return py3compat.decode(out)
156
156
157 try:
157 try:
158 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
158 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
@@ -15,9 +15,6 This file is meant to be used by process.py
15 import os, sys, threading
15 import os, sys, threading
16 import ctypes, msvcrt
16 import ctypes, msvcrt
17
17
18 # local imports
19 from . import py3compat
20
21 # Win32 API types needed for the API calls
18 # Win32 API types needed for the API calls
22 from ctypes import POINTER
19 from ctypes import POINTER
23 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
20 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
@@ -8,6 +8,7 Utilities for working with external processes.
8
8
9
9
10 import os
10 import os
11 import shutil
11 import sys
12 import sys
12
13
13 if sys.platform == 'win32':
14 if sys.platform == 'win32':
@@ -18,7 +19,6 else:
18 from ._process_posix import system, getoutput, arg_split, check_pid
19 from ._process_posix import system, getoutput, arg_split, check_pid
19
20
20 from ._process_common import getoutputerror, get_output_error_code, process_handler
21 from ._process_common import getoutputerror, get_output_error_code, process_handler
21 from . import py3compat
22
22
23
23
24 class FindCmdError(Exception):
24 class FindCmdError(Exception):
@@ -44,7 +44,7 def find_cmd(cmd):
44 cmd : str
44 cmd : str
45 The command line program to look for.
45 The command line program to look for.
46 """
46 """
47 path = py3compat.which(cmd)
47 path = shutil.which(cmd)
48 if path is None:
48 if path is None:
49 raise FindCmdError('command could not be found: %s' % cmd)
49 raise FindCmdError('command could not be found: %s' % cmd)
50 return path
50 return path
@@ -143,153 +143,72 def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
143 return name
143 return name
144 return None
144 return None
145
145
146 if sys.version_info[0] >= 3:
146 PY3 = True
147 PY3 = True
147
148
148 # keep reference to builtin_mod because the kernel overrides that value
149 # keep reference to builtin_mod because the kernel overrides that value
149 # to forward requests to a frontend.
150 # to forward requests to a frontend.
150 def input(prompt=''):
151 def input(prompt=''):
151 return builtin_mod.input(prompt)
152 return builtin_mod.input(prompt)
152
153
153 builtin_mod_name = "builtins"
154 builtin_mod_name = "builtins"
154 import builtins as builtin_mod
155 import builtins as builtin_mod
155
156
156 str_to_unicode = no_code
157 str_to_unicode = no_code
157 unicode_to_str = no_code
158 unicode_to_str = no_code
158 str_to_bytes = encode
159 str_to_bytes = encode
159 bytes_to_str = decode
160 bytes_to_str = decode
160 cast_bytes_py2 = no_code
161 cast_bytes_py2 = no_code
161 cast_unicode_py2 = no_code
162 cast_unicode_py2 = no_code
162 buffer_to_bytes_py2 = no_code
163 buffer_to_bytes_py2 = no_code
163
164
164 string_types = (str,)
165 string_types = (str,)
165 unicode_type = str
166 unicode_type = str
166
167
167 which = shutil.which
168 which = shutil.which
168
169
169 def isidentifier(s, dotted=False):
170 def isidentifier(s, dotted=False):
170 if dotted:
171 if dotted:
171 return all(isidentifier(a) for a in s.split("."))
172 return all(isidentifier(a) for a in s.split("."))
172 return s.isidentifier()
173 return s.isidentifier()
173
174
174 xrange = range
175 xrange = range
175 def iteritems(d): return iter(d.items())
176 def iteritems(d): return iter(d.items())
176 def itervalues(d): return iter(d.values())
177 def itervalues(d): return iter(d.values())
177 getcwd = os.getcwd
178 getcwd = os.getcwd
178
179
179 MethodType = types.MethodType
180 MethodType = types.MethodType
180
181
181 def execfile(fname, glob, loc=None, compiler=None):
182 def execfile(fname, glob, loc=None, compiler=None):
182 loc = loc if (loc is not None) else glob
183 loc = loc if (loc is not None) else glob
183 with open(fname, 'rb') as f:
184 with open(fname, 'rb') as f:
184 compiler = compiler or compile
185 compiler = compiler or compile
185 exec(compiler(f.read(), fname, 'exec'), glob, loc)
186 exec(compiler(f.read(), fname, 'exec'), glob, loc)
186
187
187 # Refactor print statements in doctests.
188 # Refactor print statements in doctests.
188 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
189 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
189 def _print_statement_sub(match):
190 def _print_statement_sub(match):
190 expr = match.groups('expr')
191 expr = match.groups('expr')
191 return "print(%s)" % expr
192 return "print(%s)" % expr
192
193
193 @_modify_str_or_docstring
194 @_modify_str_or_docstring
194 def doctest_refactor_print(doc):
195 def doctest_refactor_print(doc):
195 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
196 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
196 unfortunately doesn't pick up on our doctests.
197 unfortunately doesn't pick up on our doctests.
197
198
198 Can accept a string or a function, so it can be used as a decorator."""
199 Can accept a string or a function, so it can be used as a decorator."""
199 return _print_statement_re.sub(_print_statement_sub, doc)
200 return _print_statement_re.sub(_print_statement_sub, doc)
200
201
201 # Abstract u'abc' syntax:
202 # Abstract u'abc' syntax:
202 @_modify_str_or_docstring
203 @_modify_str_or_docstring
203 def u_format(s):
204 def u_format(s):
204 """"{u}'abc'" --> "'abc'" (Python 3)
205 """"{u}'abc'" --> "'abc'" (Python 3)
205
206
206 Accepts a string or a function, so it can be used as a decorator."""
207 Accepts a string or a function, so it can be used as a decorator."""
207 return s.format(u='')
208 return s.format(u='')
208
209
209 def get_closure(f):
210 def get_closure(f):
210 """Get a function's closure attribute"""
211 """Get a function's closure attribute"""
211 return f.__closure__
212 return f.__closure__
213
214 else:
215 PY3 = False
216
217 # keep reference to builtin_mod because the kernel overrides that value
218 # to forward requests to a frontend.
219 def input(prompt=''):
220 return builtin_mod.raw_input(prompt)
221
222 builtin_mod_name = "__builtin__"
223 import __builtin__ as builtin_mod
224
225 str_to_unicode = decode
226 unicode_to_str = encode
227 str_to_bytes = no_code
228 bytes_to_str = no_code
229 cast_bytes_py2 = cast_bytes
230 cast_unicode_py2 = cast_unicode
231 buffer_to_bytes_py2 = buffer_to_bytes
232
233 string_types = (str, unicode)
234 unicode_type = unicode
235
236 import re
237 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
238 def isidentifier(s, dotted=False):
239 if dotted:
240 return all(isidentifier(a) for a in s.split("."))
241 return bool(_name_re.match(s))
242
243 xrange = xrange
244 def iteritems(d): return d.iteritems()
245 def itervalues(d): return d.itervalues()
246 getcwd = os.getcwdu
247
248 def MethodType(func, instance):
249 return types.MethodType(func, instance, type(instance))
250
251 def doctest_refactor_print(func_or_str):
252 return func_or_str
253
254 def get_closure(f):
255 """Get a function's closure attribute"""
256 return f.func_closure
257
258 which = _shutil_which
259
260 # Abstract u'abc' syntax:
261 @_modify_str_or_docstring
262 def u_format(s):
263 """"{u}'abc'" --> "u'abc'" (Python 2)
264
265 Accepts a string or a function, so it can be used as a decorator."""
266 return s.format(u='u')
267
268 if sys.platform == 'win32':
269 def execfile(fname, glob=None, loc=None, compiler=None):
270 loc = loc if (loc is not None) else glob
271 scripttext = builtin_mod.open(fname).read()+ '\n'
272 # compile converts unicode filename to str assuming
273 # ascii. Let's do the conversion before calling compile
274 if isinstance(fname, unicode):
275 filename = unicode_to_str(fname)
276 else:
277 filename = fname
278 compiler = compiler or compile
279 exec(compiler(scripttext, filename, 'exec'), glob, loc)
280
281 else:
282 def execfile(fname, glob=None, loc=None, compiler=None):
283