##// END OF EJS Templates
Fix imports of builtins module
Thomas Kluyver -
Show More
@@ -23,7 +23,6 b' Authors'
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import __builtin__ as builtin_mod
27 import argparse
26 import argparse
28 import copy
27 import copy
29 import os
28 import os
@@ -33,6 +32,7 b' import sys'
33 from IPython.utils.path import filefind, get_ipython_dir
32 from IPython.utils.path import filefind, get_ipython_dir
34 from IPython.utils import py3compat, warn
33 from IPython.utils import py3compat, warn
35 from IPython.utils.encoding import DEFAULT_ENCODING
34 from IPython.utils.encoding import DEFAULT_ENCODING
35 from IPython.utils.py3compat import builtin_mod
36 from IPython.utils.traitlets import HasTraits, List, Any, TraitError
36 from IPython.utils.traitlets import HasTraits, List, Any, TraitError
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
@@ -18,10 +18,9 b' Authors:'
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 import __builtin__
22
23 from IPython.config.configurable import Configurable
21 from IPython.config.configurable import Configurable
24
22
23 from IPython.utils.py3compat import builtin_mod
25 from IPython.utils.traitlets import Instance
24 from IPython.utils.traitlets import Instance
26
25
27 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
@@ -78,7 +77,7 b' class BuiltinTrap(Configurable):'
78
77
79 def add_builtin(self, key, value):
78 def add_builtin(self, key, value):
80 """Add a builtin and save the original."""
79 """Add a builtin and save the original."""
81 bdict = __builtin__.__dict__
80 bdict = builtin_mod.__dict__
82 orig = bdict.get(key, BuiltinUndefined)
81 orig = bdict.get(key, BuiltinUndefined)
83 if value is HideBuiltin:
82 if value is HideBuiltin:
84 if orig is not BuiltinUndefined: #same as 'key in bdict'
83 if orig is not BuiltinUndefined: #same as 'key in bdict'
@@ -91,9 +90,9 b' class BuiltinTrap(Configurable):'
91 def remove_builtin(self, key, orig):
90 def remove_builtin(self, key, orig):
92 """Remove an added builtin and re-set the original."""
91 """Remove an added builtin and re-set the original."""
93 if orig is BuiltinUndefined:
92 if orig is BuiltinUndefined:
94 del __builtin__.__dict__[key]
93 del builtin_mod.__dict__[key]
95 else:
94 else:
96 __builtin__.__dict__[key] = orig
95 builtin_mod.__dict__[key] = orig
97
96
98 def activate(self):
97 def activate(self):
99 """Store ipython references in the __builtin__ namespace."""
98 """Store ipython references in the __builtin__ namespace."""
@@ -66,7 +66,6 b' Notes:'
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 import __builtin__
70 import __main__
69 import __main__
71 import glob
70 import glob
72 import inspect
71 import inspect
@@ -83,6 +82,7 b' from IPython.utils import generics'
83 from IPython.utils import io
82 from IPython.utils import io
84 from IPython.utils.dir2 import dir2
83 from IPython.utils.dir2 import dir2
85 from IPython.utils.process import arg_split
84 from IPython.utils.process import arg_split
85 from IPython.utils.py3compat import builtin_mod
86 from IPython.utils.traitlets import CBool, Enum
86 from IPython.utils.traitlets import CBool, Enum
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
@@ -353,7 +353,7 b' class Completer(Configurable):'
353 match_append = matches.append
353 match_append = matches.append
354 n = len(text)
354 n = len(text)
355 for lst in [keyword.kwlist,
355 for lst in [keyword.kwlist,
356 __builtin__.__dict__.keys(),
356 builtin_mod.__dict__.keys(),
357 self.namespace.keys(),
357 self.namespace.keys(),
358 self.global_namespace.keys()]:
358 self.global_namespace.keys()]:
359 for word in lst:
359 for word in lst:
@@ -23,13 +23,12 b' Authors:'
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 from __future__ import print_function
24 from __future__ import print_function
25
25
26 import __builtin__
27
28 import sys
26 import sys
29
27
30
28
31 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
32 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.py3compat import builtin_mod
33 from IPython.utils.traitlets import Instance
32 from IPython.utils.traitlets import Instance
34 from IPython.utils.warn import warn
33 from IPython.utils.warn import warn
35
34
@@ -90,7 +89,7 b' class DisplayHook(Configurable):'
90 # If something injected a '_' variable in __builtin__, delete
89 # If something injected a '_' variable in __builtin__, delete
91 # ipython's automatic one so we don't clobber that. gettext() in
90 # ipython's automatic one so we don't clobber that. gettext() in
92 # particular uses _, so we need to stay away from it.
91 # particular uses _, so we need to stay away from it.
93 if '_' in __builtin__.__dict__:
92 if '_' in builtin_mod.__dict__:
94 try:
93 try:
95 del self.shell.user_ns['_']
94 del self.shell.user_ns['_']
96 except KeyError:
95 except KeyError:
@@ -206,7 +205,7 b' class DisplayHook(Configurable):'
206 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
205 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
207 # we cause buggy behavior for things like gettext).
206 # we cause buggy behavior for things like gettext).
208
207
209 if '_' not in __builtin__.__dict__:
208 if '_' not in builtin_mod.__dict__:
210 self.___ = self.__
209 self.___ = self.__
211 self.__ = self._
210 self.__ = self._
212 self._ = result
211 self._ = result
@@ -270,7 +269,7 b' class DisplayHook(Configurable):'
270 # Release our own references to objects:
269 # Release our own references to objects:
271 self._, self.__, self.___ = '', '', ''
270 self._, self.__, self.___ = '', '', ''
272
271
273 if '_' not in __builtin__.__dict__:
272 if '_' not in builtin_mod.__dict__:
274 self.shell.user_ns.update({'_':None,'__':None, '___':None})
273 self.shell.user_ns.update({'_':None,'__':None, '___':None})
275 import gc
274 import gc
276 # TODO: Is this really needed?
275 # TODO: Is this really needed?
@@ -17,7 +17,6 b''
17 from __future__ import absolute_import
17 from __future__ import absolute_import
18 from __future__ import print_function
18 from __future__ import print_function
19
19
20 import __builtin__ as builtin_mod
21 import __future__
20 import __future__
22 import abc
21 import abc
23 import ast
22 import ast
@@ -69,6 +68,7 b' from IPython.utils.ipstruct import Struct'
69 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
70 from IPython.utils.pickleshare import PickleShareDB
69 from IPython.utils.pickleshare import PickleShareDB
71 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import builtin_mod
72 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.text import (format_screen, LSString, SList,
74 from IPython.utils.text import (format_screen, LSString, SList,
@@ -15,7 +15,6 b' from __future__ import print_function'
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 # Stdlib
17 # Stdlib
18 import __builtin__ as builtin_mod
19 import ast
18 import ast
20 import bdb
19 import bdb
21 import os
20 import os
@@ -44,6 +43,7 b' from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,'
44 line_cell_magic, on_off, needs_local_scope)
43 line_cell_magic, on_off, needs_local_scope)
45 from IPython.testing.skipdoctest import skip_doctest
44 from IPython.testing.skipdoctest import skip_doctest
46 from IPython.utils import py3compat
45 from IPython.utils import py3compat
46 from IPython.utils.py3compat import builtin_mod
47 from IPython.utils.contexts import preserve_keys
47 from IPython.utils.contexts import preserve_keys
48 from IPython.utils.io import capture_output
48 from IPython.utils.io import capture_output
49 from IPython.utils.ipstruct import Struct
49 from IPython.utils.ipstruct import Struct
@@ -1,9 +1,9 b''
1 import __builtin__
2 import sys
1 import sys
3
2
4 from IPython.core.displayhook import DisplayHook
3 from IPython.core.displayhook import DisplayHook
5 from IPython.kernel.inprocess.socket import SocketABC
4 from IPython.kernel.inprocess.socket import SocketABC
6 from IPython.utils.jsonutil import encode_images
5 from IPython.utils.jsonutil import encode_images
6 from IPython.utils.py3compat import builtin_mod
7 from IPython.utils.traitlets import Instance, Dict
7 from IPython.utils.traitlets import Instance, Dict
8 from .session import extract_header, Session
8 from .session import extract_header, Session
9
9
@@ -21,7 +21,7 b' class ZMQDisplayHook(object):'
21 if obj is None:
21 if obj is None:
22 return
22 return
23
23
24 __builtin__._ = obj
24 builtin_mod._ = obj
25 sys.stdout.flush()
25 sys.stdout.flush()
26 sys.stderr.flush()
26 sys.stderr.flush()
27 msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)},
27 msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)},
@@ -7,7 +7,6 b''
7 from __future__ import print_function
7 from __future__ import print_function
8
8
9 # Standard library imports
9 # Standard library imports
10 import __builtin__
11 import sys
10 import sys
12 import time
11 import time
13 import traceback
12 import traceback
@@ -29,6 +28,7 b' from IPython.config.configurable import Configurable'
29 from IPython.core.error import StdinNotImplementedError
28 from IPython.core.error import StdinNotImplementedError
30 from IPython.core import release
29 from IPython.core import release
31 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.py3compat import builtin_mod
32 from IPython.utils.jsonutil import json_clean
32 from IPython.utils.jsonutil import json_clean
33 from IPython.utils.traitlets import (
33 from IPython.utils.traitlets import (
34 Any, Instance, Float, Dict, List, Set, Integer, Unicode,
34 Any, Instance, Float, Dict, List, Set, Integer, Unicode,
@@ -356,13 +356,13 b' class Kernel(Configurable):'
356 raw_input = input = lambda prompt='' : self._no_raw_input()
356 raw_input = input = lambda prompt='' : self._no_raw_input()
357
357
358 if py3compat.PY3:
358 if py3compat.PY3:
359 self._sys_raw_input = __builtin__.input
359 self._sys_raw_input = builtin_mod.input
360 __builtin__.input = raw_input
360 builtin_mod.input = raw_input
361 else:
361 else:
362 self._sys_raw_input = __builtin__.raw_input
362 self._sys_raw_input = builtin_mod.raw_input
363 self._sys_eval_input = __builtin__.input
363 self._sys_eval_input = builtin_mod.input
364 __builtin__.raw_input = raw_input
364 builtin_mod.raw_input = raw_input
365 __builtin__.input = input
365 builtin_mod.input = input
366
366
367 # Set the parent message of the display hook and out streams.
367 # Set the parent message of the display hook and out streams.
368 shell.set_parent(parent)
368 shell.set_parent(parent)
@@ -392,10 +392,10 b' class Kernel(Configurable):'
392 finally:
392 finally:
393 # Restore raw_input.
393 # Restore raw_input.
394 if py3compat.PY3:
394 if py3compat.PY3:
395 __builtin__.input = self._sys_raw_input
395 builtin_mod.input = self._sys_raw_input
396 else:
396 else:
397 __builtin__.raw_input = self._sys_raw_input
397 builtin_mod.raw_input = self._sys_raw_input
398 __builtin__.input = self._sys_eval_input
398 builtin_mod.input = self._sys_eval_input
399
399
400 reply_content[u'status'] = status
400 reply_content[u'status'] = status
401
401
@@ -25,7 +25,6 b' from __future__ import print_function'
25 # the file COPYING, distributed as part of this software.
25 # the file COPYING, distributed as part of this software.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 import __builtin__
29 from contextlib import contextmanager
28 from contextlib import contextmanager
30 import imp
29 import imp
31 import sys
30 import sys
@@ -33,16 +32,18 b' import sys'
33 from types import ModuleType
32 from types import ModuleType
34 from warnings import warn
33 from warnings import warn
35
34
36 original_import = __builtin__.__import__
35 from IPython.utils.py3compat import builtin_mod, builtin_mod_name
36
37 original_import = builtin_mod.__import__
37
38
38 @contextmanager
39 @contextmanager
39 def replace_import_hook(new_import):
40 def replace_import_hook(new_import):
40 saved_import = __builtin__.__import__
41 saved_import = builtin_mod.__import__
41 __builtin__.__import__ = new_import
42 builtin_mod.__import__ = new_import
42 try:
43 try:
43 yield
44 yield
44 finally:
45 finally:
45 __builtin__.__import__ = saved_import
46 builtin_mod.__import__ = saved_import
46
47
47 def get_parent(globals, level):
48 def get_parent(globals, level):
48 """
49 """
@@ -313,12 +314,12 b' def deep_reload_hook(m):'
313
314
314 # Save the original hooks
315 # Save the original hooks
315 try:
316 try:
316 original_reload = __builtin__.reload
317 original_reload = builtin_mod.reload
317 except AttributeError:
318 except AttributeError:
318 original_reload = imp.reload # Python 3
319 original_reload = imp.reload # Python 3
319
320
320 # Replacement for reload()
321 # Replacement for reload()
321 def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):
322 def reload(module, exclude=['sys', 'os.path', builtin_mod_name, '__main__']):
322 """Recursively reload all modules used in the given module. Optionally
323 """Recursively reload all modules used in the given module. Optionally
323 takes a list of modules to exclude from reloading. The default exclude
324 takes a list of modules to exclude from reloading. The default exclude
324 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
325 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
@@ -335,4 +336,4 b" def reload(module, exclude=['sys', 'os.path', '__builtin__', '__main__']):"
335
336
336 # Uncomment the following to automatically activate deep reloading whenever
337 # Uncomment the following to automatically activate deep reloading whenever
337 # this module is imported
338 # this module is imported
338 #__builtin__.reload = reload
339 #builtin_mod.reload = reload
@@ -10,6 +10,7 b' import os'
10 import nose.tools as nt
10 import nose.tools as nt
11
11
12 from IPython.testing import decorators as dec
12 from IPython.testing import decorators as dec
13 from IPython.utils.py3compat import builtin_mod_name
13 from IPython.utils.syspathcontext import prepended_to_syspath
14 from IPython.utils.syspathcontext import prepended_to_syspath
14 from IPython.utils.tempdir import TemporaryDirectory
15 from IPython.utils.tempdir import TemporaryDirectory
15 from IPython.lib.deepreload import reload as dreload
16 from IPython.lib.deepreload import reload as dreload
@@ -24,7 +25,7 b' def test_deepreload_numpy():'
24 import numpy
25 import numpy
25 exclude = [
26 exclude = [
26 # Standard exclusions:
27 # Standard exclusions:
27 'sys', 'os.path', '__builtin__', '__main__',
28 'sys', 'os.path', builtin_mod_name, '__main__',
28 # Test-related exclusions:
29 # Test-related exclusions:
29 'unittest', 'UserDict',
30 'unittest', 'UserDict',
30 ]
31 ]
@@ -440,8 +440,8 b' class DirectView(View):'
440 importing recarray from numpy on engine(s)
440 importing recarray from numpy on engine(s)
441
441
442 """
442 """
443 import __builtin__
443 from IPython.utils.py3compat import builtin_mod
444 local_import = __builtin__.__import__
444 local_import = builtin_mod.__import__
445 modules = set()
445 modules = set()
446 results = []
446 results = []
447 @util.interactive
447 @util.interactive
@@ -463,8 +463,8 b' class DirectView(View):'
463 locally as well.
463 locally as well.
464 """
464 """
465 # don't override nested imports
465 # don't override nested imports
466 save_import = __builtin__.__import__
466 save_import = builtin_mod.__import__
467 __builtin__.__import__ = local_import
467 builtin_mod.__import__ = local_import
468
468
469 if imp.lock_held():
469 if imp.lock_held():
470 # this is a side-effect import, don't do it remotely, or even
470 # this is a side-effect import, don't do it remotely, or even
@@ -488,12 +488,12 b' class DirectView(View):'
488 print("importing %s on engine(s)"%name)
488 print("importing %s on engine(s)"%name)
489 results.append(self.apply_async(remote_import, name, fromlist, level))
489 results.append(self.apply_async(remote_import, name, fromlist, level))
490 # restore override
490 # restore override
491 __builtin__.__import__ = save_import
491 builtin_mod.__import__ = save_import
492
492
493 return mod
493 return mod
494
494
495 # override __import__
495 # override __import__
496 __builtin__.__import__ = view_import
496 builtin_mod.__import__ = view_import
497 try:
497 try:
498 # enter the block
498 # enter the block
499 yield
499 yield
@@ -505,7 +505,7 b' class DirectView(View):'
505 pass
505 pass
506 finally:
506 finally:
507 # always restore __import__
507 # always restore __import__
508 __builtin__.__import__ = local_import
508 builtin_mod.__import__ = local_import
509
509
510 for r in results:
510 for r in results:
511 # raise possible remote ImportErrors here
511 # raise possible remote ImportErrors here
@@ -20,7 +20,6 b' from __future__ import print_function'
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # stdlib
22 # stdlib
23 import __builtin__ as builtin_mod
24 import os
23 import os
25 import sys
24 import sys
26
25
@@ -30,6 +29,7 b' from . import tools'
30 from IPython.core import page
29 from IPython.core import page
31 from IPython.utils import io
30 from IPython.utils import io
32 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.py3compat import builtin_mod
33 from IPython.terminal.interactiveshell import TerminalInteractiveShell
33 from IPython.terminal.interactiveshell import TerminalInteractiveShell
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
@@ -19,7 +19,6 b' Limitations:'
19 # Module imports
19 # Module imports
20
20
21 # From the standard library
21 # From the standard library
22 import __builtin__ as builtin_mod
23 import commands
22 import commands
24 import doctest
23 import doctest
25 import inspect
24 import inspect
@@ -48,6 +47,7 b' from nose.plugins import doctests, Plugin'
48 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
47 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
49
48
50 # Our own imports
49 # Our own imports
50 from IPython.utils.py3compat import builtin_mod
51
51
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53 # Module globals and other constants
53 # Module globals and other constants
@@ -296,7 +296,7 b' class DocTestCase(doctests.DocTestCase):'
296 # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
296 # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
297 # it does look like one to me: its tearDown method tries to run
297 # it does look like one to me: its tearDown method tries to run
298 #
298 #
299 # delattr(__builtin__, self._result_var)
299 # delattr(builtin_mod, self._result_var)
300 #
300 #
301 # without checking that the attribute really is there; it implicitly
301 # without checking that the attribute really is there; it implicitly
302 # assumes it should have been set via displayhook. But if the
302 # assumes it should have been set via displayhook. But if the
@@ -1,6 +1,5 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__
4 import functools
3 import functools
5 import sys
4 import sys
6 import re
5 import re
@@ -76,6 +75,7 b' if sys.version_info[0] >= 3:'
76
75
77 input = input
76 input = input
78 builtin_mod_name = "builtins"
77 builtin_mod_name = "builtins"
78 import builtins as builtin_mod
79
79
80 str_to_unicode = no_code
80 str_to_unicode = no_code
81 unicode_to_str = no_code
81 unicode_to_str = no_code
@@ -127,6 +127,7 b' else:'
127
127
128 input = raw_input
128 input = raw_input
129 builtin_mod_name = "__builtin__"
129 builtin_mod_name = "__builtin__"
130 import __builtin__ as builtin_mod
130
131
131 str_to_unicode = decode
132 str_to_unicode = decode
132 unicode_to_str = encode
133 unicode_to_str = encode
@@ -189,7 +190,7 b' else:'
189 # The rstrip() is necessary b/c trailing whitespace in files will
190 # The rstrip() is necessary b/c trailing whitespace in files will
190 # 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,
191 # but we still support 2.6). See issue 1027.
192 # but we still support 2.6). See issue 1027.
192 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
193 scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
193 # compile converts unicode filename to str assuming
194 # compile converts unicode filename to str assuming
194 # ascii. Let's do the conversion before calling compile
195 # ascii. Let's do the conversion before calling compile
195 if isinstance(fname, unicode):
196 if isinstance(fname, unicode):
@@ -203,4 +204,4 b' else:'
203 filename = fname.encode(sys.getfilesystemencoding())
204 filename = fname.encode(sys.getfilesystemencoding())
204 else:
205 else:
205 filename = fname
206 filename = fname
206 __builtin__.execfile(filename, *where)
207 builtin_mod.execfile(filename, *where)
General Comments 0
You need to be logged in to leave comments. Login now