##// END OF EJS Templates
Merge pull request #10105 from srinivasreddy/dead_code...
Thomas Kluyver -
r23070:748d7071 merge
parent child Browse files
Show More
@@ -27,7 +27,6 b' import sys'
27 from traitlets.config.configurable import Configurable
27 from traitlets.config.configurable import Configurable
28 from IPython.core.error import UsageError
28 from IPython.core.error import UsageError
29
29
30 from IPython.utils.py3compat import string_types
31 from traitlets import List, Instance
30 from traitlets import List, Instance
32 from logging import error
31 from logging import error
33
32
@@ -148,7 +147,7 b' class Alias(object):'
148 raise InvalidAliasError("The name %s can't be aliased "
147 raise InvalidAliasError("The name %s can't be aliased "
149 "because it is another magic command." % self.name)
148 "because it is another magic command." % self.name)
150
149
151 if not (isinstance(self.cmd, string_types)):
150 if not (isinstance(self.cmd, str)):
152 raise InvalidAliasError("An alias command must be a string, "
151 raise InvalidAliasError("An alias command must be a string, "
153 "got: %r" % self.cmd)
152 "got: %r" % self.cmd)
154
153
@@ -126,7 +126,7 b' class BaseIPythonApplication(Application):'
126 config_file_paths = List(Unicode())
126 config_file_paths = List(Unicode())
127 @default('config_file_paths')
127 @default('config_file_paths')
128 def _config_file_paths_default(self):
128 def _config_file_paths_default(self):
129 return [py3compat.getcwd()]
129 return [os.getcwd()]
130
130
131 extra_config_file = Unicode(
131 extra_config_file = Unicode(
132 help="""Path to an extra config file to load.
132 help="""Path to an extra config file to load.
@@ -215,7 +215,7 b' class BaseIPythonApplication(Application):'
215 super(BaseIPythonApplication, self).__init__(**kwargs)
215 super(BaseIPythonApplication, self).__init__(**kwargs)
216 # ensure current working directory exists
216 # ensure current working directory exists
217 try:
217 try:
218 py3compat.getcwd()
218 os.getcwd()
219 except:
219 except:
220 # exit if cwd doesn't exist
220 # exit if cwd doesn't exist
221 self.log.error("Current working directory doesn't exist.")
221 self.log.error("Current working directory doesn't exist.")
@@ -20,7 +20,7 b' Authors:'
20
20
21 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
22
22
23 from IPython.utils.py3compat import builtin_mod, iteritems
23 from IPython.utils.py3compat import builtin_mod
24 from traitlets import Instance
24 from traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
@@ -90,14 +90,14 b' class BuiltinTrap(Configurable):'
90 """Store ipython references in the __builtin__ namespace."""
90 """Store ipython references in the __builtin__ namespace."""
91
91
92 add_builtin = self.add_builtin
92 add_builtin = self.add_builtin
93 for name, func in iteritems(self.auto_builtins):
93 for name, func in self.auto_builtins.items():
94 add_builtin(name, func)
94 add_builtin(name, func)
95
95
96 def deactivate(self):
96 def deactivate(self):
97 """Remove any builtins which might have been added by add_builtins, or
97 """Remove any builtins which might have been added by add_builtins, or
98 restore overwritten ones to their previous values."""
98 restore overwritten ones to their previous values."""
99 remove_builtin = self.remove_builtin
99 remove_builtin = self.remove_builtin
100 for key, val in iteritems(self._orig_builtins):
100 for key, val in self._orig_builtins.items():
101 remove_builtin(key, val)
101 remove_builtin(key, val)
102 self._orig_builtins.clear()
102 self._orig_builtins.clear()
103 self._builtins_added = False
103 self._builtins_added = False
@@ -35,7 +35,7 b' from IPython.utils import generics'
35 from IPython.utils.decorators import undoc
35 from IPython.utils.decorators import undoc
36 from IPython.utils.dir2 import dir2, get_real_method
36 from IPython.utils.dir2 import dir2, get_real_method
37 from IPython.utils.process import arg_split
37 from IPython.utils.process import arg_split
38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
38 from IPython.utils.py3compat import builtin_mod, PY3, cast_unicode_py2
39 from traitlets import Bool, Enum, observe
39 from traitlets import Bool, Enum, observe
40
40
41 from functools import wraps
41 from functools import wraps
@@ -423,14 +423,14 b' def get__all__entries(obj):'
423 except:
423 except:
424 return []
424 return []
425
425
426 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
426 return [cast_unicode_py2(w) for w in words if isinstance(w, str)]
427
427
428
428
429 def match_dict_keys(keys, prefix, delims):
429 def match_dict_keys(keys, prefix, delims):
430 """Used by dict_key_matches, matching the prefix to a list of keys"""
430 """Used by dict_key_matches, matching the prefix to a list of keys"""
431 if not prefix:
431 if not prefix:
432 return None, 0, [repr(k) for k in keys
432 return None, 0, [repr(k) for k in keys
433 if isinstance(k, (string_types, bytes))]
433 if isinstance(k, (str, bytes))]
434 quote_match = re.search('["\']', prefix)
434 quote_match = re.search('["\']', prefix)
435 quote = quote_match.group()
435 quote = quote_match.group()
436 try:
436 try:
@@ -33,7 +33,6 b' from zipimport import zipimporter'
33 from IPython.core.completer import expand_user, compress_user
33 from IPython.core.completer import expand_user, compress_user
34 from IPython.core.error import TryNext
34 from IPython.core.error import TryNext
35 from IPython.utils._process_common import arg_split
35 from IPython.utils._process_common import arg_split
36 from IPython.utils.py3compat import string_types
37
36
38 # FIXME: this should be pulled in with the right call via the component system
37 # FIXME: this should be pulled in with the right call via the component system
39 from IPython import get_ipython
38 from IPython import get_ipython
@@ -164,7 +163,7 b' def try_import(mod, only_modules=False):'
164 completions.extend(getattr(m, '__all__', []))
163 completions.extend(getattr(m, '__all__', []))
165 if m_is_init:
164 if m_is_init:
166 completions.extend(module_list(os.path.dirname(m.__file__)))
165 completions.extend(module_list(os.path.dirname(m.__file__)))
167 completions = {c for c in completions if isinstance(c, string_types)}
166 completions = {c for c in completions if isinstance(c, str)}
168 completions.discard('__init__')
167 completions.discard('__init__')
169 return list(completions)
168 return list(completions)
170
169
@@ -188,7 +187,7 b' def quick_completer(cmd, completions):'
188 [d:\ipython]|3> foo ba
187 [d:\ipython]|3> foo ba
189 """
188 """
190
189
191 if isinstance(completions, string_types):
190 if isinstance(completions, str):
192 completions = completions.split()
191 completions = completions.split()
193
192
194 def do_complete(self, event):
193 def do_complete(self, event):
@@ -27,7 +27,7 b' from pprint import pformat'
27 from IPython.core import ultratb
27 from IPython.core import ultratb
28 from IPython.core.release import author_email
28 from IPython.core.release import author_email
29 from IPython.utils.sysinfo import sys_info
29 from IPython.utils.sysinfo import sys_info
30 from IPython.utils.py3compat import input, getcwd
30 from IPython.utils.py3compat import input
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Code
33 # Code
@@ -139,9 +139,9 b' class CrashHandler(object):'
139 try:
139 try:
140 rptdir = self.app.ipython_dir
140 rptdir = self.app.ipython_dir
141 except:
141 except:
142 rptdir = getcwd()
142 rptdir = os.getcwd()
143 if rptdir is None or not os.path.isdir(rptdir):
143 if rptdir is None or not os.path.isdir(rptdir):
144 rptdir = getcwd()
144 rptdir = os.getcwd()
145 report_name = os.path.join(rptdir,self.crash_report_fname)
145 report_name = os.path.join(rptdir,self.crash_report_fname)
146 # write the report filename into the instance dict so it can get
146 # write the report filename into the instance dict so it can get
147 # properly expanded out in the user message template
147 # properly expanded out in the user message template
@@ -18,8 +18,7 b' import struct'
18 import sys
18 import sys
19 import warnings
19 import warnings
20
20
21 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
21 from IPython.utils.py3compat import cast_bytes_py2, cast_unicode
22 unicode_type)
23 from IPython.testing.skipdoctest import skip_doctest
22 from IPython.testing.skipdoctest import skip_doctest
24
23
25 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
@@ -481,7 +480,7 b' class DisplayObject(object):'
481 filename : unicode
480 filename : unicode
482 Path to a local file to load the data from.
481 Path to a local file to load the data from.
483 """
482 """
484 if data is not None and isinstance(data, string_types):
483 if data is not None and isinstance(data, str):
485 if data.startswith('http') and url is None:
484 if data.startswith('http') and url is None:
486 url = data
485 url = data
487 filename = None
486 filename = None
@@ -493,7 +492,7 b' class DisplayObject(object):'
493
492
494 self.data = data
493 self.data = data
495 self.url = url
494 self.url = url
496 self.filename = None if filename is None else unicode_type(filename)
495 self.filename = filename
497
496
498 self.reload()
497 self.reload()
499 self._check_data()
498 self._check_data()
@@ -539,7 +538,7 b' class DisplayObject(object):'
539 class TextDisplayObject(DisplayObject):
538 class TextDisplayObject(DisplayObject):
540 """Validate that display data is text"""
539 """Validate that display data is text"""
541 def _check_data(self):
540 def _check_data(self):
542 if self.data is not None and not isinstance(self.data, string_types):
541 if self.data is not None and not isinstance(self.data, str):
543 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
542 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
544
543
545 class Pretty(TextDisplayObject):
544 class Pretty(TextDisplayObject):
@@ -657,7 +656,7 b' class JSON(DisplayObject):'
657
656
658 @data.setter
657 @data.setter
659 def data(self, data):
658 def data(self, data):
660 if isinstance(data, string_types):
659 if isinstance(data, str):
661 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
660 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
662 data = json.loads(data)
661 data = json.loads(data)
663 self._data = data
662 self._data = data
@@ -715,11 +714,11 b' class Javascript(TextDisplayObject):'
715 The full URLs of the css files should be given. A single css URL
714 The full URLs of the css files should be given. A single css URL
716 can also be given as a string.
715 can also be given as a string.
717 """
716 """
718 if isinstance(lib, string_types):
717 if isinstance(lib, str):
719 lib = [lib]
718 lib = [lib]
720 elif lib is None:
719 elif lib is None:
721 lib = []
720 lib = []
722 if isinstance(css, string_types):
721 if isinstance(css, str):
723 css = [css]
722 css = [css]
724 elif css is None:
723 elif css is None:
725 css = []
724 css = []
@@ -848,7 +847,7 b' class Image(DisplayObject):'
848 ext = self._find_ext(url)
847 ext = self._find_ext(url)
849 elif data is None:
848 elif data is None:
850 raise ValueError("No image data found. Expecting filename, url, or data.")
849 raise ValueError("No image data found. Expecting filename, url, or data.")
851 elif isinstance(data, string_types) and (
850 elif isinstance(data, str) and (
852 data.startswith('http') or _safe_exists(data)
851 data.startswith('http') or _safe_exists(data)
853 ):
852 ):
854 ext = self._find_ext(data)
853 ext = self._find_ext(data)
@@ -877,7 +876,7 b' class Image(DisplayObject):'
877 # jpg->jpeg
876 # jpg->jpeg
878 format = self._FMT_JPEG
877 format = self._FMT_JPEG
879
878
880 self.format = unicode_type(format).lower()
879 self.format = format.lower()
881 self.embed = embed if embed is not None else (url is None)
880 self.embed = embed if embed is not None else (url is None)
882
881
883 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
882 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
@@ -954,7 +953,7 b' class Image(DisplayObject):'
954 return self._data_and_metadata()
953 return self._data_and_metadata()
955
954
956 def _find_ext(self, s):
955 def _find_ext(self, s):
957 return unicode_type(s.split('.')[-1].lower())
956 return s.split('.')[-1].lower()
958
957
959 class Video(DisplayObject):
958 class Video(DisplayObject):
960
959
@@ -999,7 +998,7 b' class Video(DisplayObject):'
999 Video('path/to/video.mp4', embed=True)
998 Video('path/to/video.mp4', embed=True)
1000 Video(b'raw-videodata', embed=True)
999 Video(b'raw-videodata', embed=True)
1001 """
1000 """
1002 if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
1001 if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
1003 url = data
1002 url = data
1004 data = None
1003 data = None
1005 elif os.path.exists(data):
1004 elif os.path.exists(data):
@@ -1038,7 +1037,7 b' class Video(DisplayObject):'
1038 video = f.read()
1037 video = f.read()
1039 else:
1038 else:
1040 video = self.data
1039 video = self.data
1041 if isinstance(video, unicode_type):
1040 if isinstance(video, str):
1042 # unicode input is already b64-encoded
1041 # unicode input is already b64-encoded
1043 b64_video = video
1042 b64_video = video
1044 else:
1043 else:
@@ -29,7 +29,7 b' from traitlets import ('
29 default, observe,
29 default, observe,
30 )
30 )
31 from IPython.utils.py3compat import (
31 from IPython.utils.py3compat import (
32 with_metaclass, string_types, unicode_type,
32 with_metaclass
33 )
33 )
34
34
35
35
@@ -276,7 +276,7 b' class BaseFormatter(Configurable):'
276 """
276 """
277
277
278 format_type = Unicode('text/plain')
278 format_type = Unicode('text/plain')
279 _return_type = string_types
279 _return_type = str
280
280
281 enabled = Bool(True).tag(config=True)
281 enabled = Bool(True).tag(config=True)
282
282
@@ -376,7 +376,7 b' class BaseFormatter(Configurable):'
376 ------
376 ------
377 KeyError if the type has not been registered.
377 KeyError if the type has not been registered.
378 """
378 """
379 if isinstance(typ, string_types):
379 if isinstance(typ, str):
380 typ_key = tuple(typ.rsplit('.',1))
380 typ_key = tuple(typ.rsplit('.',1))
381 if typ_key not in self.deferred_printers:
381 if typ_key not in self.deferred_printers:
382 # We may have it cached in the type map. We will have to
382 # We may have it cached in the type map. We will have to
@@ -419,7 +419,7 b' class BaseFormatter(Configurable):'
419 this will be the previous value (to enable restoring later).
419 this will be the previous value (to enable restoring later).
420 """
420 """
421 # if string given, interpret as 'pkg.module.class_name'
421 # if string given, interpret as 'pkg.module.class_name'
422 if isinstance(typ, string_types):
422 if isinstance(typ, str):
423 type_module, type_name = typ.rsplit('.', 1)
423 type_module, type_name = typ.rsplit('.', 1)
424 return self.for_type_by_name(type_module, type_name, func)
424 return self.for_type_by_name(type_module, type_name, func)
425
425
@@ -491,7 +491,7 b' class BaseFormatter(Configurable):'
491 KeyError if the type is not registered and default is not specified.
491 KeyError if the type is not registered and default is not specified.
492 """
492 """
493
493
494 if isinstance(typ, string_types):
494 if isinstance(typ, str):
495 typ_key = tuple(typ.rsplit('.',1))
495 typ_key = tuple(typ.rsplit('.',1))
496 if typ_key not in self.deferred_printers:
496 if typ_key not in self.deferred_printers:
497 # We may have it cached in the type map. We will have to
497 # We may have it cached in the type map. We will have to
@@ -737,7 +737,7 b' class PNGFormatter(BaseFormatter):'
737
737
738 print_method = ObjectName('_repr_png_')
738 print_method = ObjectName('_repr_png_')
739
739
740 _return_type = (bytes, unicode_type)
740 _return_type = (bytes, str)
741
741
742
742
743 class JPEGFormatter(BaseFormatter):
743 class JPEGFormatter(BaseFormatter):
@@ -755,7 +755,7 b' class JPEGFormatter(BaseFormatter):'
755
755
756 print_method = ObjectName('_repr_jpeg_')
756 print_method = ObjectName('_repr_jpeg_')
757
757
758 _return_type = (bytes, unicode_type)
758 _return_type = (bytes, str)
759
759
760
760
761 class LatexFormatter(BaseFormatter):
761 class LatexFormatter(BaseFormatter):
@@ -804,7 +804,7 b' class JSONFormatter(BaseFormatter):'
804 r, md = r
804 r, md = r
805
805
806 # handle deprecated JSON-as-string form from IPython < 3
806 # handle deprecated JSON-as-string form from IPython < 3
807 if isinstance(r, string_types):
807 if isinstance(r, str):
808 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
808 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
809 FormatterWarning)
809 FormatterWarning)
810 r = json.loads(r)
810 r = json.loads(r)
@@ -846,7 +846,7 b' class PDFFormatter(BaseFormatter):'
846
846
847 print_method = ObjectName('_repr_pdf_')
847 print_method = ObjectName('_repr_pdf_')
848
848
849 _return_type = (bytes, unicode_type)
849 _return_type = (bytes, str)
850
850
851 class IPythonDisplayFormatter(BaseFormatter):
851 class IPythonDisplayFormatter(BaseFormatter):
852 """A Formatter for objects that know how to display themselves.
852 """A Formatter for objects that know how to display themselves.
@@ -487,7 +487,7 b' class HistoryManager(HistoryAccessor):'
487 @default('dir_hist')
487 @default('dir_hist')
488 def _dir_hist_default(self):
488 def _dir_hist_default(self):
489 try:
489 try:
490 return [py3compat.getcwd()]
490 return [os.getcwd()]
491 except OSError:
491 except OSError:
492 return []
492 return []
493
493
@@ -593,7 +593,7 b' class HistoryManager(HistoryAccessor):'
593 optionally open a new session."""
593 optionally open a new session."""
594 self.output_hist.clear()
594 self.output_hist.clear()
595 # The directory history can't be completely empty
595 # The directory history can't be completely empty
596 self.dir_hist[:] = [py3compat.getcwd()]
596 self.dir_hist[:] = [os.getcwd()]
597
597
598 if new_session:
598 if new_session:
599 if self.session_number:
599 if self.session_number:
@@ -67,8 +67,7 b' from IPython.utils.ipstruct import Struct'
67 from IPython.paths import get_ipython_dir
67 from IPython.paths import get_ipython_dir
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
70 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
70 from IPython.utils.py3compat import builtin_mod, with_metaclass
71 with_metaclass, iteritems)
72 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
73 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
@@ -550,7 +549,7 b' class InteractiveShell(SingletonConfigurable):'
550
549
551 # keep track of where we started running (mainly for crash post-mortem)
550 # keep track of where we started running (mainly for crash post-mortem)
552 # This is not being used anywhere currently.
551 # This is not being used anywhere currently.
553 self.starting_dir = py3compat.getcwd()
552 self.starting_dir = os.getcwd()
554
553
555 # Indentation management
554 # Indentation management
556 self.indent_current_nsp = 0
555 self.indent_current_nsp = 0
@@ -733,7 +732,7 b' class InteractiveShell(SingletonConfigurable):'
733 def restore_sys_module_state(self):
732 def restore_sys_module_state(self):
734 """Restore the state of the sys module."""
733 """Restore the state of the sys module."""
735 try:
734 try:
736 for k, v in iteritems(self._orig_sys_module_state):
735 for k, v in self._orig_sys_module_state.items():
737 setattr(sys, k, v)
736 setattr(sys, k, v)
738 except AttributeError:
737 except AttributeError:
739 pass
738 pass
@@ -1255,7 +1254,7 b' class InteractiveShell(SingletonConfigurable):'
1255 # Also check in output history
1254 # Also check in output history
1256 ns_refs.append(self.history_manager.output_hist)
1255 ns_refs.append(self.history_manager.output_hist)
1257 for ns in ns_refs:
1256 for ns in ns_refs:
1258 to_delete = [n for n, o in iteritems(ns) if o is obj]
1257 to_delete = [n for n, o in ns.items() if o is obj]
1259 for name in to_delete:
1258 for name in to_delete:
1260 del ns[name]
1259 del ns[name]
1261
1260
@@ -1307,8 +1306,8 b' class InteractiveShell(SingletonConfigurable):'
1307 # We need a dict of name/value pairs to do namespace updates.
1306 # We need a dict of name/value pairs to do namespace updates.
1308 if isinstance(variables, dict):
1307 if isinstance(variables, dict):
1309 vdict = variables
1308 vdict = variables
1310 elif isinstance(variables, string_types+(list, tuple)):
1309 elif isinstance(variables, (str, list, tuple)):
1311 if isinstance(variables, string_types):
1310 if isinstance(variables, str):
1312 vlist = variables.split()
1311 vlist = variables.split()
1313 else:
1312 else:
1314 vlist = variables
1313 vlist = variables
@@ -1347,7 +1346,7 b' class InteractiveShell(SingletonConfigurable):'
1347 variables : dict
1346 variables : dict
1348 A dictionary mapping object names (as strings) to the objects.
1347 A dictionary mapping object names (as strings) to the objects.
1349 """
1348 """
1350 for name, obj in iteritems(variables):
1349 for name, obj in variables.items():
1351 if name in self.user_ns and self.user_ns[name] is obj:
1350 if name in self.user_ns and self.user_ns[name] is obj:
1352 del self.user_ns[name]
1351 del self.user_ns[name]
1353 self.user_ns_hidden.pop(name, None)
1352 self.user_ns_hidden.pop(name, None)
@@ -1651,14 +1650,14 b' class InteractiveShell(SingletonConfigurable):'
1651 msg = "CustomTB must return list of strings, not %r" % stb
1650 msg = "CustomTB must return list of strings, not %r" % stb
1652 if stb is None:
1651 if stb is None:
1653 return []
1652 return []
1654 elif isinstance(stb, string_types):
1653 elif isinstance(stb, str):
1655 return [stb]
1654 return [stb]
1656 elif not isinstance(stb, list):
1655 elif not isinstance(stb, list):
1657 raise TypeError(msg)
1656 raise TypeError(msg)
1658 # it's a list
1657 # it's a list
1659 for line in stb:
1658 for line in stb:
1660 # check every element
1659 # check every element
1661 if not isinstance(line, string_types):
1660 if not isinstance(line, str):
1662 raise TypeError(msg)
1661 raise TypeError(msg)
1663 return stb
1662 return stb
1664
1663
@@ -2154,7 +2153,7 b' class InteractiveShell(SingletonConfigurable):'
2154
2153
2155 from IPython.core import macro
2154 from IPython.core import macro
2156
2155
2157 if isinstance(themacro, string_types):
2156 if isinstance(themacro, str):
2158 themacro = macro.Macro(themacro)
2157 themacro = macro.Macro(themacro)
2159 if not isinstance(themacro, macro.Macro):
2158 if not isinstance(themacro, macro.Macro):
2160 raise ValueError('A macro must be a string or a Macro instance.')
2159 raise ValueError('A macro must be a string or a Macro instance.')
@@ -2203,14 +2202,12 b' class InteractiveShell(SingletonConfigurable):'
2203 with AvoidUNCPath() as path:
2202 with AvoidUNCPath() as path:
2204 if path is not None:
2203 if path is not None:
2205 cmd = '"pushd %s &&"%s' % (path, cmd)
2204 cmd = '"pushd %s &&"%s' % (path, cmd)
2206 cmd = py3compat.unicode_to_str(cmd)
2207 try:
2205 try:
2208 ec = os.system(cmd)
2206 ec = os.system(cmd)
2209 except KeyboardInterrupt:
2207 except KeyboardInterrupt:
2210 print('\n' + self.get_exception_only(), file=sys.stderr)
2208 print('\n' + self.get_exception_only(), file=sys.stderr)
2211 ec = -2
2209 ec = -2
2212 else:
2210 else:
2213 cmd = py3compat.unicode_to_str(cmd)
2214 # For posix the result of the subprocess.call() below is an exit
2211 # For posix the result of the subprocess.call() below is an exit
2215 # code, which by convention is zero for success, positive for
2212 # code, which by convention is zero for success, positive for
2216 # program failure. Exit codes above 128 are reserved for signals,
2213 # program failure. Exit codes above 128 are reserved for signals,
@@ -2343,7 +2340,7 b' class InteractiveShell(SingletonConfigurable):'
2343 exc_info = {
2340 exc_info = {
2344 u'status' : 'error',
2341 u'status' : 'error',
2345 u'traceback' : stb,
2342 u'traceback' : stb,
2346 u'ename' : unicode_type(etype.__name__),
2343 u'ename' : etype.__name__,
2347 u'evalue' : py3compat.safe_unicode(evalue),
2344 u'evalue' : py3compat.safe_unicode(evalue),
2348 }
2345 }
2349
2346
@@ -2382,7 +2379,7 b' class InteractiveShell(SingletonConfigurable):'
2382 user_ns = self.user_ns
2379 user_ns = self.user_ns
2383 global_ns = self.user_global_ns
2380 global_ns = self.user_global_ns
2384
2381
2385 for key, expr in iteritems(expressions):
2382 for key, expr in expressions.items():
2386 try:
2383 try:
2387 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2384 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2388 except:
2385 except:
@@ -3165,7 +3162,7 b' class InteractiveShell(SingletonConfigurable):'
3165 raise ValueError(("'%s' was not found in history, as a file, url, "
3162 raise ValueError(("'%s' was not found in history, as a file, url, "
3166 "nor in the user namespace.") % target)
3163 "nor in the user namespace.") % target)
3167
3164
3168 if isinstance(codeobj, string_types):
3165 if isinstance(codeobj, str):
3169 return codeobj
3166 return codeobj
3170 elif isinstance(codeobj, Macro):
3167 elif isinstance(codeobj, Macro):
3171 return codeobj.value
3168 return codeobj.value
@@ -18,7 +18,6 b' import io'
18 import os
18 import os
19 import time
19 import time
20
20
21 from IPython.utils.py3compat import str_to_unicode
22
21
23 #****************************************************************************
22 #****************************************************************************
24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
@@ -193,8 +192,7 b' which already exists. But you must first start the logging process with'
193 write = self.logfile.write
192 write = self.logfile.write
194 if kind=='input':
193 if kind=='input':
195 if self.timestamp:
194 if self.timestamp:
196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
195 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', time.localtime()))
197 time.localtime())))
198 write(data)
196 write(data)
199 elif kind=='output' and self.log_output:
197 elif kind=='output' and self.log_output:
200 odata = u'\n'.join([u'#[Out]# %s' % s
198 odata = u'\n'.join([u'#[Out]# %s' % s
@@ -37,7 +37,7 b' class Macro(object):'
37 self.value = code + '\n'
37 self.value = code + '\n'
38
38
39 def __str__(self):
39 def __str__(self):
40 return py3compat.unicode_to_str(self.value)
40 return self.value
41
41
42 def __unicode__(self):
42 def __unicode__(self):
43 return self.value
43 return self.value
@@ -52,6 +52,6 b' class Macro(object):'
52 def __add__(self, other):
52 def __add__(self, other):
53 if isinstance(other, Macro):
53 if isinstance(other, Macro):
54 return Macro(self.value + other.value)
54 return Macro(self.value + other.value)
55 elif isinstance(other, py3compat.string_types):
55 elif isinstance(other, str):
56 return Macro(self.value + other)
56 return Macro(self.value + other)
57 raise TypeError
57 raise TypeError
@@ -24,7 +24,6 b' from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2'
24 from decorator import decorator
24 from decorator import decorator
25 from IPython.utils.ipstruct import Struct
25 from IPython.utils.ipstruct import Struct
26 from IPython.utils.process import arg_split
26 from IPython.utils.process import arg_split
27 from IPython.utils.py3compat import string_types, iteritems
28 from IPython.utils.text import dedent
27 from IPython.utils.text import dedent
29 from traitlets import Bool, Dict, Instance, observe
28 from traitlets import Bool, Dict, Instance, observe
30 from logging import error
29 from logging import error
@@ -192,7 +191,7 b' def _method_magic_marker(magic_kind):'
192 name = func.__name__
191 name = func.__name__
193 retval = decorator(call, func)
192 retval = decorator(call, func)
194 record_magic(magics, magic_kind, name, name)
193 record_magic(magics, magic_kind, name, name)
195 elif isinstance(arg, string_types):
194 elif isinstance(arg, str):
196 # Decorator called with arguments (@foo('bar'))
195 # Decorator called with arguments (@foo('bar'))
197 name = arg
196 name = arg
198 def mark(func, *a, **kw):
197 def mark(func, *a, **kw):
@@ -237,7 +236,7 b' def _function_magic_marker(magic_kind):'
237 name = func.__name__
236 name = func.__name__
238 ip.register_magic_function(func, magic_kind, name)
237 ip.register_magic_function(func, magic_kind, name)
239 retval = decorator(call, func)
238 retval = decorator(call, func)
240 elif isinstance(arg, string_types):
239 elif isinstance(arg, str):
241 # Decorator called with arguments (@foo('bar'))
240 # Decorator called with arguments (@foo('bar'))
242 name = arg
241 name = arg
243 def mark(func, *a, **kw):
242 def mark(func, *a, **kw):
@@ -344,7 +343,7 b' class MagicsManager(Configurable):'
344 docs = {}
343 docs = {}
345 for m_type in self.magics:
344 for m_type in self.magics:
346 m_docs = {}
345 m_docs = {}
347 for m_name, m_func in iteritems(self.magics[m_type]):
346 for m_name, m_func in self.magics[m_type].items():
348 if m_func.__doc__:
347 if m_func.__doc__:
349 if brief:
348 if brief:
350 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
349 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
@@ -510,8 +509,8 b' class Magics(Configurable):'
510 for mtype in magic_kinds:
509 for mtype in magic_kinds:
511 tab = self.magics[mtype] = {}
510 tab = self.magics[mtype] = {}
512 cls_tab = class_magics[mtype]
511 cls_tab = class_magics[mtype]
513 for magic_name, meth_name in iteritems(cls_tab):
512 for magic_name, meth_name in cls_tab.items():
514 if isinstance(meth_name, string_types):
513 if isinstance(meth_name, str):
515 # it's a method name, grab it
514 # it's a method name, grab it
516 tab[magic_name] = getattr(self, meth_name)
515 tab[magic_name] = getattr(self, meth_name)
517 else:
516 else:
@@ -12,7 +12,6 b' from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes'
12 from IPython.utils.text import format_screen, dedent, indent
12 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.testing.skipdoctest import skip_doctest
13 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.utils.ipstruct import Struct
14 from IPython.utils.ipstruct import Struct
15 from IPython.utils.py3compat import unicode_type
16 from warnings import warn
15 from warnings import warn
17 from logging import error
16 from logging import error
18
17
@@ -550,7 +549,7 b' Currently the magic system has the following functions:""",'
550 help=argparse.SUPPRESS
549 help=argparse.SUPPRESS
551 )
550 )
552 @magic_arguments.argument(
551 @magic_arguments.argument(
553 'filename', type=unicode_type,
552 'filename', type=str,
554 help='Notebook name or filename'
553 help='Notebook name or filename'
555 )
554 )
556 @line_magic
555 @line_magic
@@ -28,7 +28,6 b' from IPython.core.magic import Magics, magics_class, line_magic'
28 from IPython.core.oinspect import find_file, find_source_lines
28 from IPython.core.oinspect import find_file, find_source_lines
29 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.py3compat import string_types
32 from IPython.utils.contexts import preserve_keys
31 from IPython.utils.contexts import preserve_keys
33 from IPython.utils.path import get_py_filename
32 from IPython.utils.path import get_py_filename
34 from warnings import warn
33 from warnings import warn
@@ -443,7 +442,7 b' class CodeMagics(Magics):'
443
442
444 #print '*** args',args,'type',type(args) # dbg
443 #print '*** args',args,'type',type(args) # dbg
445 data = eval(args, shell.user_ns)
444 data = eval(args, shell.user_ns)
446 if not isinstance(data, string_types):
445 if not isinstance(data, str):
447 raise DataIsObject
446 raise DataIsObject
448
447
449 except (NameError,SyntaxError):
448 except (NameError,SyntaxError):
@@ -36,7 +36,7 b' from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,'
36 line_cell_magic, on_off, needs_local_scope)
36 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
38 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
39 from IPython.utils.py3compat import builtin_mod, PY3
40 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
@@ -1279,8 +1279,7 b' python-profiler package from non-free.""")'
1279 """
1279 """
1280 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1280 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1281 if not args: # List existing macros
1281 if not args: # List existing macros
1282 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1282 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1283 isinstance(v, Macro))
1284 if len(args) == 1:
1283 if len(args) == 1:
1285 raise UsageError(
1284 raise UsageError(
1286 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1285 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
@@ -19,7 +19,6 b' import sys'
19 # Our own packages
19 # Our own packages
20 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
21 from warnings import warn
21 from warnings import warn
22 from IPython.utils.py3compat import str_to_unicode
23
22
24 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
25 # Magic implementation classes
24 # Magic implementation classes
@@ -138,7 +137,7 b' class LoggingMagics(Magics):'
138 for n in range(1,len(input_hist)-1):
137 for n in range(1,len(input_hist)-1):
139 log_write(input_hist[n].rstrip() + u'\n')
138 log_write(input_hist[n].rstrip() + u'\n')
140 if n in output_hist:
139 if n in output_hist:
141 log_write(str_to_unicode(repr(output_hist[n])),'output')
140 log_write(repr(output_hist[n]),'output')
142 else:
141 else:
143 logger.log_write(u'\n'.join(input_hist[1:]))
142 logger.log_write(u'\n'.join(input_hist[1:]))
144 logger.log_write(u'\n')
143 logger.log_write(u'\n')
@@ -25,7 +25,6 b' from IPython.testing.skipdoctest import skip_doctest'
25 from IPython.utils.encoding import DEFAULT_ENCODING
25 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.openpy import read_py_file
26 from IPython.utils.openpy import read_py_file
27 from IPython.utils.path import get_py_filename
27 from IPython.utils.path import get_py_filename
28 from IPython.utils.py3compat import unicode_type
29
28
30 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
31 # Magic implementation classes
30 # Magic implementation classes
@@ -460,7 +459,7 b' class NamespaceMagics(Magics):'
460 try:
459 try:
461 vstr = str(var)
460 vstr = str(var)
462 except UnicodeEncodeError:
461 except UnicodeEncodeError:
463 vstr = unicode_type(var).encode(DEFAULT_ENCODING,
462 vstr = var.encode(DEFAULT_ENCODING,
464 'backslashreplace')
463 'backslashreplace')
465 except:
464 except:
466 vstr = "<object with id %d (str() failed)>" % id(var)
465 vstr = "<object with id %d (str() failed)>" % id(var)
@@ -35,7 +35,6 b' from IPython.testing.skipdoctest import skip_doctest'
35 from IPython.utils.openpy import source_to_unicode
35 from IPython.utils.openpy import source_to_unicode
36 from IPython.utils.process import abbrev_cwd
36 from IPython.utils.process import abbrev_cwd
37 from IPython.utils import py3compat
37 from IPython.utils import py3compat
38 from IPython.utils.py3compat import unicode_type
39 from IPython.utils.terminal import set_term_title
38 from IPython.utils.terminal import set_term_title
40
39
41 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
@@ -178,7 +177,7 b' class OSMagics(Magics):'
178 winext += '|py'
177 winext += '|py'
179 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
178 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
180 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
179 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
181 savedir = py3compat.getcwd()
180 savedir = os.getcwd()
182
181
183 # Now walk the paths looking for executables to alias.
182 # Now walk the paths looking for executables to alias.
184 try:
183 try:
@@ -240,7 +239,7 b' class OSMagics(Magics):'
240 In [9]: pwd
239 In [9]: pwd
241 Out[9]: '/home/tsuser/sprint/ipython'
240 Out[9]: '/home/tsuser/sprint/ipython'
242 """
241 """
243 return py3compat.getcwd()
242 return os.getcwd()
244
243
245 @skip_doctest
244 @skip_doctest
246 @line_magic
245 @line_magic
@@ -284,7 +283,7 b' class OSMagics(Magics):'
284 /home/tsuser/parent/child
283 /home/tsuser/parent/child
285 """
284 """
286
285
287 oldcwd = py3compat.getcwd()
286 oldcwd = os.getcwd()
288 numcd = re.match(r'(-)(\d+)$',parameter_s)
287 numcd = re.match(r'(-)(\d+)$',parameter_s)
289 # jump in directory history by number
288 # jump in directory history by number
290 if numcd:
289 if numcd:
@@ -352,7 +351,7 b' class OSMagics(Magics):'
352 except OSError:
351 except OSError:
353 print(sys.exc_info()[1])
352 print(sys.exc_info()[1])
354 else:
353 else:
355 cwd = py3compat.getcwd()
354 cwd = os.getcwd()
356 dhist = self.shell.user_ns['_dh']
355 dhist = self.shell.user_ns['_dh']
357 if oldcwd != cwd:
356 if oldcwd != cwd:
358 dhist.append(cwd)
357 dhist.append(cwd)
@@ -362,7 +361,7 b' class OSMagics(Magics):'
362 os.chdir(self.shell.home_dir)
361 os.chdir(self.shell.home_dir)
363 if hasattr(self.shell, 'term_title') and self.shell.term_title:
362 if hasattr(self.shell, 'term_title') and self.shell.term_title:
364 set_term_title('IPython: ' + '~')
363 set_term_title('IPython: ' + '~')
365 cwd = py3compat.getcwd()
364 cwd = os.getcwd()
366 dhist = self.shell.user_ns['_dh']
365 dhist = self.shell.user_ns['_dh']
367
366
368 if oldcwd != cwd:
367 if oldcwd != cwd:
@@ -437,7 +436,7 b' class OSMagics(Magics):'
437
436
438 dir_s = self.shell.dir_stack
437 dir_s = self.shell.dir_stack
439 tgt = os.path.expanduser(parameter_s)
438 tgt = os.path.expanduser(parameter_s)
440 cwd = py3compat.getcwd().replace(self.shell.home_dir,'~')
439 cwd = os.getcwd().replace(self.shell.home_dir,'~')
441 if tgt:
440 if tgt:
442 self.cd(parameter_s)
441 self.cd(parameter_s)
443 dir_s.insert(0,cwd)
442 dir_s.insert(0,cwd)
@@ -725,7 +724,7 b' class OSMagics(Magics):'
725 if not args:
724 if not args:
726 raise UsageError("%bookmark: You must specify the bookmark name")
725 raise UsageError("%bookmark: You must specify the bookmark name")
727 elif len(args)==1:
726 elif len(args)==1:
728 bkms[args[0]] = py3compat.getcwd()
727 bkms[args[0]] = os.getcwd()
729 elif len(args)==2:
728 elif len(args)==2:
730 bkms[args[0]] = args[1]
729 bkms[args[0]] = args[1]
731 self.shell.db['bookmarks'] = bkms
730 self.shell.db['bookmarks'] = bkms
@@ -764,7 +763,7 b' class OSMagics(Magics):'
764 'The file will be created if it does not exist.'
763 'The file will be created if it does not exist.'
765 )
764 )
766 @magic_arguments.argument(
765 @magic_arguments.argument(
767 'filename', type=unicode_type,
766 'filename', type=str,
768 help='file to write'
767 help='file to write'
769 )
768 )
770 @cell_magic
769 @cell_magic
@@ -35,7 +35,7 b' from IPython.utils.path import compress_user'
35 from IPython.utils.text import indent
35 from IPython.utils.text import indent
36 from IPython.utils.wildcard import list_namespace
36 from IPython.utils.wildcard import list_namespace
37 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
37 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
38 from IPython.utils.py3compat import cast_unicode, string_types, PY3
38 from IPython.utils.py3compat import cast_unicode, PY3
39 from IPython.utils.colorable import Colorable
39 from IPython.utils.colorable import Colorable
40 from IPython.utils.decorators import undoc
40 from IPython.utils.decorators import undoc
41
41
@@ -124,7 +124,7 b' def getdoc(obj):'
124 pass
124 pass
125 else:
125 else:
126 # if we get extra info, we add it to the normal docstring.
126 # if we get extra info, we add it to the normal docstring.
127 if isinstance(ds, string_types):
127 if isinstance(ds, str):
128 return inspect.cleandoc(ds)
128 return inspect.cleandoc(ds)
129 try:
129 try:
130 docstr = inspect.getdoc(obj)
130 docstr = inspect.getdoc(obj)
@@ -180,10 +180,10 b' class ProfileList(Application):'
180 print("Available profiles in %s:" % self.ipython_dir)
180 print("Available profiles in %s:" % self.ipython_dir)
181 self._print_profiles(profiles)
181 self._print_profiles(profiles)
182
182
183 profiles = list_profiles_in(py3compat.getcwd())
183 profiles = list_profiles_in(os.getcwd())
184 if profiles:
184 if profiles:
185 print()
185 print()
186 print("Available profiles in current directory (%s):" % py3compat.getcwd())
186 print("Available profiles in current directory (%s):" % os.getcwd())
187 self._print_profiles(profiles)
187 self._print_profiles(profiles)
188
188
189 print()
189 print()
@@ -187,7 +187,7 b' class ProfileDir(LoggingConfigurable):'
187 is not found, a :class:`ProfileDirError` exception will be raised.
187 is not found, a :class:`ProfileDirError` exception will be raised.
188
188
189 The search path algorithm is:
189 The search path algorithm is:
190 1. ``py3compat.getcwd()``
190 1. ``os.getcwd()``
191 2. ``ipython_dir``
191 2. ``ipython_dir``
192
192
193 Parameters
193 Parameters
@@ -199,7 +199,7 b' class ProfileDir(LoggingConfigurable):'
199 will be "profile_<profile>".
199 will be "profile_<profile>".
200 """
200 """
201 dirname = u'profile_' + name
201 dirname = u'profile_' + name
202 paths = [py3compat.getcwd(), ipython_dir]
202 paths = [os.getcwd(), ipython_dir]
203 for p in paths:
203 for p in paths:
204 profile_dir = os.path.join(p, dirname)
204 profile_dir = os.path.join(p, dirname)
205 if os.path.isdir(profile_dir):
205 if os.path.isdir(profile_dir):
@@ -19,8 +19,5 b' class LazyEvaluate(object):'
19 def __str__(self):
19 def __str__(self):
20 return str(self())
20 return str(self())
21
21
22 def __unicode__(self):
23 return py3compat.unicode_type(self())
24
25 def __format__(self, format_spec):
22 def __format__(self, format_spec):
26 return format(self(), format_spec)
23 return format(self(), format_spec)
@@ -217,7 +217,7 b' def select_figure_formats(shell, formats, **kwargs):'
217 jpg_formatter = shell.display_formatter.formatters['image/jpeg']
217 jpg_formatter = shell.display_formatter.formatters['image/jpeg']
218 pdf_formatter = shell.display_formatter.formatters['application/pdf']
218 pdf_formatter = shell.display_formatter.formatters['application/pdf']
219
219
220 if isinstance(formats, py3compat.string_types):
220 if isinstance(formats, str):
221 formats = {formats}
221 formats = {formats}
222 # cast in case of list / tuple
222 # cast in case of list / tuple
223 formats = set(formats)
223 formats = set(formats)
@@ -19,9 +19,9 b' def test_unicode_cwd():'
19 """Check that IPython starts with non-ascii characters in the path."""
19 """Check that IPython starts with non-ascii characters in the path."""
20 wd = tempfile.mkdtemp(suffix=u"€")
20 wd = tempfile.mkdtemp(suffix=u"€")
21
21
22 old_wd = py3compat.getcwd()
22 old_wd = os.getcwd()
23 os.chdir(wd)
23 os.chdir(wd)
24 #raise Exception(repr(py3compat.getcwd()))
24 #raise Exception(repr(os.getcwd()))
25 try:
25 try:
26 app = BaseIPythonApplication()
26 app = BaseIPythonApplication()
27 # The lines below are copied from Application.initialize()
27 # The lines below are copied from Application.initialize()
@@ -42,7 +42,7 b' def test_unicode_ipdir():'
42
42
43 old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
43 old_ipdir1 = os.environ.pop("IPYTHONDIR", None)
44 old_ipdir2 = os.environ.pop("IPYTHON_DIR", None)
44 old_ipdir2 = os.environ.pop("IPYTHON_DIR", None)
45 os.environ["IPYTHONDIR"] = py3compat.unicode_to_str(ipdir, "utf-8")
45 os.environ["IPYTHONDIR"] = ipdir
46 try:
46 try:
47 app = BaseIPythonApplication()
47 app = BaseIPythonApplication()
48 # The lines below are copied from Application.initialize()
48 # The lines below are copied from Application.initialize()
@@ -18,7 +18,6 b' from IPython.core import completer'
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21 from IPython.utils.py3compat import string_types, unicode_type
22 from IPython.testing import decorators as dec
21 from IPython.testing import decorators as dec
23
22
24 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
@@ -102,7 +101,7 b' def test_line_split():'
102 check_line_split(sp, t)
101 check_line_split(sp, t)
103 # Ensure splitting works OK with unicode by re-running the tests with
102 # Ensure splitting works OK with unicode by re-running the tests with
104 # all inputs turned into unicode
103 # all inputs turned into unicode
105 check_line_split(sp, [ map(unicode_type, p) for p in t] )
104 check_line_split(sp, [ map(str, p) for p in t] )
106
105
107
106
108 def test_custom_completion_error():
107 def test_custom_completion_error():
@@ -123,13 +122,13 b' def test_unicode_completions():'
123 # Some strings that trigger different types of completion. Check them both
122 # Some strings that trigger different types of completion. Check them both
124 # in str and unicode forms
123 # in str and unicode forms
125 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
124 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
126 for t in s + list(map(unicode_type, s)):
125 for t in s + list(map(str, s)):
127 # We don't need to check exact completion values (they may change
126 # We don't need to check exact completion values (they may change
128 # depending on the state of the namespace, but at least no exceptions
127 # depending on the state of the namespace, but at least no exceptions
129 # should be thrown and the return value should be a pair of text, list
128 # should be thrown and the return value should be a pair of text, list
130 # values.
129 # values.
131 text, matches = ip.complete(t)
130 text, matches = ip.complete(t)
132 nt.assert_true(isinstance(text, string_types))
131 nt.assert_true(isinstance(text, str))
133 nt.assert_true(isinstance(matches, list))
132 nt.assert_true(isinstance(matches, list))
134
133
135 def test_latex_completions():
134 def test_latex_completions():
@@ -41,7 +41,7 b' class Test_magic_run_completer(unittest.TestCase):'
41 for d in self.dirs:
41 for d in self.dirs:
42 os.mkdir(join(self.BASETESTDIR, d))
42 os.mkdir(join(self.BASETESTDIR, d))
43
43
44 self.oldpath = py3compat.getcwd()
44 self.oldpath = os.getcwd()
45 os.chdir(self.BASETESTDIR)
45 os.chdir(self.BASETESTDIR)
46
46
47 def tearDown(self):
47 def tearDown(self):
@@ -94,7 +94,7 b' class Test_magic_run_completer_nonascii(unittest.TestCase):'
94 for fil in [u"aaø.py", u"a.py", u"b.py"]:
94 for fil in [u"aaø.py", u"a.py", u"b.py"]:
95 with open(join(self.BASETESTDIR, fil), "w") as sfile:
95 with open(join(self.BASETESTDIR, fil), "w") as sfile:
96 sfile.write("pass\n")
96 sfile.write("pass\n")
97 self.oldpath = py3compat.getcwd()
97 self.oldpath = os.getcwd()
98 os.chdir(self.BASETESTDIR)
98 os.chdir(self.BASETESTDIR)
99
99
100 def tearDown(self):
100 def tearDown(self):
@@ -157,6 +157,6 b' def test_bad_module_all():'
157 results = module_completion('from bad_all import ')
157 results = module_completion('from bad_all import ')
158 nt.assert_in('puppies', results)
158 nt.assert_in('puppies', results)
159 for r in results:
159 for r in results:
160 nt.assert_is_instance(r, py3compat.string_types)
160 nt.assert_is_instance(r, str)
161 finally:
161 finally:
162 sys.path.remove(testsdir)
162 sys.path.remove(testsdir)
@@ -15,7 +15,7 b' from IPython.core.inputtransformer import InputTransformer'
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
16 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils import py3compat
17 from IPython.utils import py3compat
18 from IPython.utils.py3compat import string_types, input
18 from IPython.utils.py3compat import input
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Semi-complete examples (also used as tests)
21 # Semi-complete examples (also used as tests)
@@ -100,7 +100,7 b' def test_remove_comments():'
100
100
101 def test_get_input_encoding():
101 def test_get_input_encoding():
102 encoding = isp.get_input_encoding()
102 encoding = isp.get_input_encoding()
103 nt.assert_true(isinstance(encoding, string_types))
103 nt.assert_true(isinstance(encoding, str))
104 # simple-minded check that at least encoding a simple string works with the
104 # simple-minded check that at least encoding a simple string works with the
105 # encoding we got.
105 # encoding we got.
106 nt.assert_equal(u'test'.encode(encoding), b'test')
106 nt.assert_equal(u'test'.encode(encoding), b'test')
@@ -32,7 +32,7 b' from IPython.testing.decorators import ('
32 from IPython.testing import tools as tt
32 from IPython.testing import tools as tt
33 from IPython.utils.process import find_cmd
33 from IPython.utils.process import find_cmd
34 from IPython.utils import py3compat
34 from IPython.utils import py3compat
35 from IPython.utils.py3compat import unicode_type, PY3
35 from IPython.utils.py3compat import PY3
36
36
37 if PY3:
37 if PY3:
38 from io import StringIO
38 from io import StringIO
@@ -473,7 +473,7 b' class InteractiveShellTestCase(unittest.TestCase):'
473 def test_inspect_text(self):
473 def test_inspect_text(self):
474 ip.run_cell('a = 5')
474 ip.run_cell('a = 5')
475 text = ip.object_inspect_text('a')
475 text = ip.object_inspect_text('a')
476 self.assertIsInstance(text, unicode_type)
476 self.assertIsInstance(text, str)
477
477
478
478
479 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
479 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
@@ -485,7 +485,7 b' class TestSafeExecfileNonAsciiPath(unittest.TestCase):'
485 os.mkdir(self.TESTDIR)
485 os.mkdir(self.TESTDIR)
486 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
486 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
487 sfile.write("pass\n")
487 sfile.write("pass\n")
488 self.oldpath = py3compat.getcwd()
488 self.oldpath = os.getcwd()
489 os.chdir(self.TESTDIR)
489 os.chdir(self.TESTDIR)
490 self.fname = u"åäötestscript.py"
490 self.fname = u"åäötestscript.py"
491
491
@@ -393,9 +393,9 b' def test_parse_options():'
393
393
394 def test_dirops():
394 def test_dirops():
395 """Test various directory handling operations."""
395 """Test various directory handling operations."""
396 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
396 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
397 curpath = py3compat.getcwd
397 curpath = os.getcwd
398 startdir = py3compat.getcwd()
398 startdir = os.getcwd()
399 ipdir = os.path.realpath(_ip.ipython_dir)
399 ipdir = os.path.realpath(_ip.ipython_dir)
400 try:
400 try:
401 _ip.magic('cd "%s"' % ipdir)
401 _ip.magic('cd "%s"' % ipdir)
@@ -121,7 +121,6 b' def test_list_profiles_in():'
121 # No need to remove these directories and files, as they will get nuked in
121 # No need to remove these directories and files, as they will get nuked in
122 # the module-level teardown.
122 # the module-level teardown.
123 td = tempfile.mkdtemp(dir=TMP_TEST_DIR)
123 td = tempfile.mkdtemp(dir=TMP_TEST_DIR)
124 td = py3compat.str_to_unicode(td)
125 for name in ('profile_foo', 'profile_hello', 'not_a_profile'):
124 for name in ('profile_foo', 'profile_hello', 'not_a_profile'):
126 os.mkdir(os.path.join(td, name))
125 os.mkdir(os.path.join(td, name))
127 if dec.unicode_paths:
126 if dec.unicode_paths:
@@ -5,7 +5,6 b' import unittest'
5
5
6 from IPython.core.prompts import LazyEvaluate
6 from IPython.core.prompts import LazyEvaluate
7 from IPython.testing.globalipapp import get_ipython
7 from IPython.testing.globalipapp import get_ipython
8 from IPython.utils.py3compat import unicode_type
9
8
10 ip = get_ipython()
9 ip = get_ipython()
11
10
@@ -14,8 +13,7 b' class PromptTests(unittest.TestCase):'
14 def test_lazy_eval_unicode(self):
13 def test_lazy_eval_unicode(self):
15 u = u'ünicødé'
14 u = u'ünicødé'
16 lz = LazyEvaluate(lambda : u)
15 lz = LazyEvaluate(lambda : u)
17 # str(lz) would fail
16 self.assertEqual(str(lz), u)
18 self.assertEqual(unicode_type(lz), u)
19 self.assertEqual(format(lz), u)
17 self.assertEqual(format(lz), u)
20
18
21 def test_lazy_eval_nonascii_bytes(self):
19 def test_lazy_eval_nonascii_bytes(self):
@@ -31,7 +29,6 b' class PromptTests(unittest.TestCase):'
31 lz = LazyEvaluate(lambda : f)
29 lz = LazyEvaluate(lambda : f)
32
30
33 self.assertEqual(str(lz), str(f))
31 self.assertEqual(str(lz), str(f))
34 self.assertEqual(unicode_type(lz), unicode_type(f))
35 self.assertEqual(format(lz), str(f))
32 self.assertEqual(format(lz), str(f))
36 self.assertEqual(format(lz, '.1'), '0.5')
33 self.assertEqual(format(lz, '.1'), '0.5')
37
34
@@ -408,7 +408,7 b' class TestMagicRunWithPackage(unittest.TestCase):'
408 self.value = int(random.random() * 10000)
408 self.value = int(random.random() * 10000)
409
409
410 self.tempdir = TemporaryDirectory()
410 self.tempdir = TemporaryDirectory()
411 self.__orig_cwd = py3compat.getcwd()
411 self.__orig_cwd = os.getcwd()
412 sys.path.insert(0, self.tempdir.name)
412 sys.path.insert(0, self.tempdir.name)
413
413
414 self.writefile(os.path.join(package, '__init__.py'), '')
414 self.writefile(os.path.join(package, '__init__.py'), '')
@@ -1060,7 +1060,7 b' class VerboseTB(TBTools):'
1060
1060
1061 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1061 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1062 try:
1062 try:
1063 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1063 names = [w for w in dir(evalue) if isinstance(w, str)]
1064 except:
1064 except:
1065 # Every now and then, an object with funny internals blows up
1065 # Every now and then, an object with funny internals blows up
1066 # when dir() is called on it. We do the best we can to report
1066 # when dir() is called on it. We do the best we can to report
@@ -1429,7 +1429,7 b' class SyntaxTB(ListTB):'
1429 # be wrong (retrieved from an outdated cache). This replaces it with
1429 # be wrong (retrieved from an outdated cache). This replaces it with
1430 # the current value.
1430 # the current value.
1431 if isinstance(value, SyntaxError) \
1431 if isinstance(value, SyntaxError) \
1432 and isinstance(value.filename, py3compat.string_types) \
1432 and isinstance(value.filename, str) \
1433 and isinstance(value.lineno, int):
1433 and isinstance(value.lineno, int):
1434 linecache.checkcache(value.filename)
1434 linecache.checkcache(value.filename)
1435 newtext = ulinecache.getline(value.filename, value.lineno)
1435 newtext = ulinecache.getline(value.filename, value.lineno)
@@ -18,7 +18,6 b' import inspect, os, sys, textwrap'
18 from IPython.core.error import UsageError
18 from IPython.core.error import UsageError
19 from IPython.core.magic import Magics, magics_class, line_magic
19 from IPython.core.magic import Magics, magics_class, line_magic
20 from traitlets import Bool
20 from traitlets import Bool
21 from IPython.utils.py3compat import string_types
22
21
23
22
24 def restore_aliases(ip):
23 def restore_aliases(ip):
@@ -178,7 +177,7 b' class StoreMagics(Magics):'
178 obj.__class__.__name__, fnam))
177 obj.__class__.__name__, fnam))
179
178
180
179
181 if not isinstance (obj, string_types):
180 if not isinstance (obj, str):
182 from pprint import pprint
181 from pprint import pprint
183 pprint(obj, fil)
182 pprint(obj, fil)
184 else:
183 else:
@@ -36,7 +36,6 b' import threading'
36 from IPython import get_ipython
36 from IPython import get_ipython
37 from IPython.core.ultratb import AutoFormattedTB
37 from IPython.core.ultratb import AutoFormattedTB
38 from logging import error
38 from logging import error
39 from IPython.utils.py3compat import string_types
40
39
41
40
42 class BackgroundJobManager(object):
41 class BackgroundJobManager(object):
@@ -171,7 +170,7 b' class BackgroundJobManager(object):'
171 if callable(func_or_exp):
170 if callable(func_or_exp):
172 kw = kwargs.get('kw',{})
171 kw = kwargs.get('kw',{})
173 job = BackgroundJobFunc(func_or_exp,*args,**kw)
172 job = BackgroundJobFunc(func_or_exp,*args,**kw)
174 elif isinstance(func_or_exp, string_types):
173 elif isinstance(func_or_exp, str):
175 if not args:
174 if not args:
176 frame = sys._getframe(1)
175 frame = sys._getframe(1)
177 glob, loc = frame.f_globals, frame.f_locals
176 glob, loc = frame.f_globals, frame.f_locals
@@ -84,7 +84,7 b' import re'
84 import datetime
84 import datetime
85 from collections import deque
85 from collections import deque
86
86
87 from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
87 from IPython.utils.py3compat import PY3, PYPY, cast_unicode
88 from IPython.utils.encoding import get_stream_enc
88 from IPython.utils.encoding import get_stream_enc
89
89
90 from io import StringIO
90 from io import StringIO
@@ -679,13 +679,13 b' def _type_pprint(obj, p, cycle):'
679 mod = _safe_getattr(obj, '__module__', None)
679 mod = _safe_getattr(obj, '__module__', None)
680 try:
680 try:
681 name = obj.__qualname__
681 name = obj.__qualname__
682 if not isinstance(name, string_types):
682 if not isinstance(name, str):
683 # This can happen if the type implements __qualname__ as a property
683 # This can happen if the type implements __qualname__ as a property
684 # or other descriptor in Python 2.
684 # or other descriptor in Python 2.
685 raise Exception("Try __name__")
685 raise Exception("Try __name__")
686 except Exception:
686 except Exception:
687 name = obj.__name__
687 name = obj.__name__
688 if not isinstance(name, string_types):
688 if not isinstance(name, str):
689 name = '<unknown type>'
689 name = '<unknown type>'
690
690
691 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
691 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
@@ -771,7 +771,6 b' except AttributeError: # Python 3'
771 _type_pprinters[slice] = _repr_pprint
771 _type_pprinters[slice] = _repr_pprint
772
772
773 try:
773 try:
774 _type_pprinters[xrange] = _repr_pprint
775 _type_pprinters[long] = _repr_pprint
774 _type_pprinters[long] = _repr_pprint
776 _type_pprinters[unicode] = _repr_pprint
775 _type_pprinters[unicode] = _repr_pprint
777 except NameError:
776 except NameError:
@@ -3,7 +3,6 b' import nose.tools as nt'
3 from IPython.core.error import TryNext
3 from IPython.core.error import TryNext
4 from IPython.lib.clipboard import ClipboardEmpty
4 from IPython.lib.clipboard import ClipboardEmpty
5 from IPython.testing.decorators import skip_if_no_x11
5 from IPython.testing.decorators import skip_if_no_x11
6 from IPython.utils.py3compat import unicode_type
7
6
8 @skip_if_no_x11
7 @skip_if_no_x11
9 def test_clipboard_get():
8 def test_clipboard_get():
@@ -19,4 +18,4 b' def test_clipboard_get():'
19 # No clipboard access API available
18 # No clipboard access API available
20 pass
19 pass
21 else:
20 else:
22 nt.assert_is_instance(a, unicode_type)
21 nt.assert_is_instance(a, str)
@@ -7,7 +7,7 b' 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 PY3, cast_unicode_py2, input, string_types
10 from IPython.utils.py3compat import PY3, cast_unicode_py2, 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 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union
13 from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union
@@ -289,7 +289,7 b' class TerminalInteractiveShell(InteractiveShell):'
289 else :
289 else :
290 raise ValueError('Got unknown colors: ', legacy)
290 raise ValueError('Got unknown colors: ', legacy)
291 else :
291 else :
292 if isinstance(name_or_cls, string_types):
292 if isinstance(name_or_cls, str):
293 style_cls = get_style_by_name(name_or_cls)
293 style_cls = get_style_by_name(name_or_cls)
294 else:
294 else:
295 style_cls = name_or_cls
295 style_cls = name_or_cls
@@ -26,7 +26,7 b' def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):'
26 prompt = ""
26 prompt = ""
27 while True:
27 while True:
28 try:
28 try:
29 l = py3compat.str_to_unicode(l_input(prompt))
29 l = l_input(prompt)
30 if l == sentinel:
30 if l == sentinel:
31 return
31 return
32 else:
32 else:
@@ -72,7 +72,7 b' class TerminalMagics(Magics):'
72 # Sanity checks
72 # Sanity checks
73 if b is None:
73 if b is None:
74 raise UsageError('No previous pasted block available')
74 raise UsageError('No previous pasted block available')
75 if not isinstance(b, py3compat.string_types):
75 if not isinstance(b, str):
76 raise UsageError(
76 raise UsageError(
77 "Variable 'pasted_block' is not a string, can't execute")
77 "Variable 'pasted_block' is not a string, can't execute")
78
78
@@ -49,7 +49,7 b' from .ipunittest import ipdoctest, ipdocstring'
49 from IPython.external.decorators import *
49 from IPython.external.decorators import *
50
50
51 # For onlyif_cmd_exists decorator
51 # For onlyif_cmd_exists decorator
52 from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
52 from IPython.utils.py3compat import which, PY2, PY3, PYPY
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Classes and functions
55 # Classes and functions
@@ -131,7 +131,7 b' def make_label_dec(label, ds=None):'
131
131
132 warnings.warn("The function `make_label_dec` is deprecated since IPython 4.0",
132 warnings.warn("The function `make_label_dec` is deprecated since IPython 4.0",
133 DeprecationWarning, stacklevel=2)
133 DeprecationWarning, stacklevel=2)
134 if isinstance(label, string_types):
134 if isinstance(label, str):
135 labels = [label]
135 labels = [label]
136 else:
136 else:
137 labels = label
137 labels = label
@@ -45,7 +45,7 b' from nose.plugins import doctests, Plugin'
45 from nose.util import anyp, tolist
45 from nose.util import anyp, tolist
46
46
47 # Our own imports
47 # Our own imports
48 from IPython.utils.py3compat import builtin_mod, PY3, getcwd
48 from IPython.utils.py3compat import builtin_mod, PY3
49
49
50 if PY3:
50 if PY3:
51 from io import StringIO
51 from io import StringIO
@@ -259,7 +259,7 b' class DocTestCase(doctests.DocTestCase):'
259 # Save our current directory and switch out to the one where the
259 # Save our current directory and switch out to the one where the
260 # test was originally created, in case another doctest did a
260 # test was originally created, in case another doctest did a
261 # directory change. We'll restore this in the finally clause.
261 # directory change. We'll restore this in the finally clause.
262 curdir = getcwd()
262 curdir = os.getcwd()
263 #print 'runTest in dir:', self._ori_dir # dbg
263 #print 'runTest in dir:', self._ori_dir # dbg
264 os.chdir(self._ori_dir)
264 os.chdir(self._ori_dir)
265
265
@@ -354,7 +354,7 b' class AssertPrints(object):'
354 """
354 """
355 def __init__(self, s, channel='stdout', suppress=True):
355 def __init__(self, s, channel='stdout', suppress=True):
356 self.s = s
356 self.s = s
357 if isinstance(self.s, (py3compat.string_types, _re_type)):
357 if isinstance(self.s, (str, _re_type)):
358 self.s = [self.s]
358 self.s = [self.s]
359 self.channel = channel
359 self.channel = channel
360 self.suppress = suppress
360 self.suppress = suppress
@@ -71,7 +71,7 b' def process_handler(cmd, callback, stderr=subprocess.PIPE):'
71 # On win32, close_fds can't be true when using pipes for stdin/out/err
71 # On win32, close_fds can't be true when using pipes for stdin/out/err
72 close_fds = sys.platform != 'win32'
72 close_fds = sys.platform != 'win32'
73 # Determine if cmd should be run with system shell.
73 # Determine if cmd should be run with system shell.
74 shell = isinstance(cmd, py3compat.string_types)
74 shell = isinstance(cmd, str)
75 # On POSIX systems run shell commands with user-preferred shell.
75 # On POSIX systems run shell commands with user-preferred shell.
76 executable = None
76 executable = None
77 if shell and os.name == 'posix' and 'SHELL' in os.environ:
77 if shell and os.name == 'posix' and 'SHELL' in os.environ:
@@ -53,7 +53,7 b' class AvoidUNCPath(object):'
53 os.system(cmd)
53 os.system(cmd)
54 """
54 """
55 def __enter__(self):
55 def __enter__(self):
56 self.path = py3compat.getcwd()
56 self.path = os.getcwd()
57 self.is_unc_path = self.path.startswith(r"\\")
57 self.is_unc_path = self.path.startswith(r"\\")
58 if self.is_unc_path:
58 if self.is_unc_path:
59 # change to c drive (as cmd.exe cannot handle UNC addresses)
59 # change to c drive (as cmd.exe cannot handle UNC addresses)
@@ -173,7 +173,7 b' class AvoidUNCPath(object):'
173 os.system(cmd)
173 os.system(cmd)
174 """
174 """
175 def __enter__(self):
175 def __enter__(self):
176 self.path = py3compat.getcwd()
176 self.path = os.getcwd()
177 self.is_unc_path = self.path.startswith(r"\\")
177 self.is_unc_path = self.path.startswith(r"\\")
178 if self.is_unc_path:
178 if self.is_unc_path:
179 # change to c drive (as cmd.exe cannot handle UNC addresses)
179 # change to c drive (as cmd.exe cannot handle UNC addresses)
@@ -9,7 +9,6 b''
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 from .py3compat import xrange
13
12
14 def uniq_stable(elems):
13 def uniq_stable(elems):
15 """uniq_stable(elems) -> list
14 """uniq_stable(elems) -> list
@@ -32,6 +31,6 b' def flatten(seq):'
32
31
33 def chop(seq, size):
32 def chop(seq, size):
34 """Chop a sequence into chunks of the given size."""
33 """Chop a sequence into chunks of the given size."""
35 return [seq[i:i+size] for i in xrange(0,len(seq),size)]
34 return [seq[i:i+size] for i in range(0,len(seq),size)]
36
35
37
36
@@ -6,7 +6,6 b''
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7
7
8 import inspect
8 import inspect
9 from .py3compat import string_types
10
9
11
10
12 def safe_hasattr(obj, attr):
11 def safe_hasattr(obj, attr):
@@ -44,7 +43,7 b' def dir2(obj):'
44 # filter out non-string attributes which may be stuffed by dir() calls
43 # filter out non-string attributes which may be stuffed by dir() calls
45 # and poor coding in third-party modules
44 # and poor coding in third-party modules
46
45
47 words = [w for w in words if isinstance(w, string_types)]
46 words = [w for w in words if isinstance(w, str)]
48 return sorted(words)
47 return sorted(words)
49
48
50
49
@@ -17,7 +17,7 b' from warnings import warn'
17
17
18 from IPython.utils.decorators import undoc
18 from IPython.utils.decorators import undoc
19 from .capture import CapturedIO, capture_output
19 from .capture import CapturedIO, capture_output
20 from .py3compat import string_types, input, PY3
20 from .py3compat import input, PY3
21
21
22 @undoc
22 @undoc
23 class IOStream:
23 class IOStream:
@@ -63,7 +63,7 b' class IOStream:'
63 def writelines(self, lines):
63 def writelines(self, lines):
64 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
64 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
65 DeprecationWarning, stacklevel=2)
65 DeprecationWarning, stacklevel=2)
66 if isinstance(lines, string_types):
66 if isinstance(lines, str):
67 lines = [lines]
67 lines = [lines]
68 for line in lines:
68 for line in lines:
69 self.write(line)
69 self.write(line)
@@ -10,7 +10,6 b' from io import TextIOWrapper, BytesIO'
10 import os.path
10 import os.path
11 import re
11 import re
12
12
13 from .py3compat import unicode_type
14
13
15 cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE)
14 cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE)
16 cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
15 cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
@@ -129,7 +128,7 b" def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):"
129 txt can be either a bytes buffer or a string containing the source
128 txt can be either a bytes buffer or a string containing the source
130 code.
129 code.
131 """
130 """
132 if isinstance(txt, unicode_type):
131 if isinstance(txt, str):
133 return txt
132 return txt
134 if isinstance(txt, bytes):
133 if isinstance(txt, bytes):
135 buffer = BytesIO(txt)
134 buffer = BytesIO(txt)
@@ -87,7 +87,6 b" def unquote_filename(name, win32=(sys.platform=='win32')):"
87 def compress_user(path):
87 def compress_user(path):
88 """Reverse of :func:`os.path.expanduser`
88 """Reverse of :func:`os.path.expanduser`
89 """
89 """
90 path = py3compat.unicode_to_str(path, sys.getfilesystemencoding())
91 home = os.path.expanduser('~')
90 home = os.path.expanduser('~')
92 if path.startswith(home):
91 if path.startswith(home):
93 path = "~" + path[len(home):]
92 path = "~" + path[len(home):]
@@ -154,11 +153,11 b' def filefind(filename, path_dirs=None):'
154
153
155 if path_dirs is None:
154 if path_dirs is None:
156 path_dirs = ("",)
155 path_dirs = ("",)
157 elif isinstance(path_dirs, py3compat.string_types):
156 elif isinstance(path_dirs, str):
158 path_dirs = (path_dirs,)
157 path_dirs = (path_dirs,)
159
158
160 for path in path_dirs:
159 for path in path_dirs:
161 if path == '.': path = py3compat.getcwd()
160 if path == '.': path = os.getcwd()
162 testname = expand_path(os.path.join(path, filename))
161 testname = expand_path(os.path.join(path, filename))
163 if os.path.isfile(testname):
162 if os.path.isfile(testname):
164 return os.path.abspath(testname)
163 return os.path.abspath(testname)
@@ -52,7 +52,7 b' def find_cmd(cmd):'
52
52
53 def abbrev_cwd():
53 def abbrev_cwd():
54 """ Return abbreviated version of cwd, e.g. d:mydir """
54 """ Return abbreviated version of cwd, e.g. d:mydir """
55 cwd = py3compat.getcwd().replace('\\','/')
55 cwd = os.getcwd().replace('\\','/')
56 drivepart = ''
56 drivepart = ''
57 tail = cwd
57 tail = cwd
58 if sys.platform == 'win32':
58 if sys.platform == 'win32':
@@ -93,7 +93,7 b" elif sys.platform == 'win32':"
93
93
94 try:
94 try:
95 # Cannot be on network share when issuing system commands
95 # Cannot be on network share when issuing system commands
96 curr = py3compat.getcwd()
96 curr = os.getcwd()
97 os.chdir("C:")
97 os.chdir("C:")
98 ret = os.system("title " + title)
98 ret = os.system("title " + title)
99 finally:
99 finally:
@@ -356,7 +356,7 b' class TestShellGlob(object):'
356 @classmethod
356 @classmethod
357 @contextmanager
357 @contextmanager
358 def in_tempdir(cls):
358 def in_tempdir(cls):
359 save = py3compat.getcwd()
359 save = os.getcwd()
360 try:
360 try:
361 os.chdir(cls.tempdir.name)
361 os.chdir(cls.tempdir.name)
362 yield
362 yield
@@ -159,7 +159,7 b' class SList(list):'
159 except IndexError:
159 except IndexError:
160 return ""
160 return ""
161
161
162 if isinstance(pattern, py3compat.string_types):
162 if isinstance(pattern, str):
163 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
163 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
164 else:
164 else:
165 pred = pattern
165 pred = pattern
@@ -307,8 +307,10 b' def list_strings(arg):'
307 Out[9]: ['A', 'list', 'of', 'strings']
307 Out[9]: ['A', 'list', 'of', 'strings']
308 """
308 """
309
309
310 if isinstance(arg, py3compat.string_types): return [arg]
310 if isinstance(arg, str):
311 else: return arg
311 return [arg]
312 else:
313 return arg
312
314
313
315
314 def marquee(txt='',width=78,mark='*'):
316 def marquee(txt='',width=78,mark='*'):
@@ -619,10 +621,10 b' def _col_chunks(l, max_rows, row_first=False):'
619 """Yield successive max_rows-sized column chunks from l."""
621 """Yield successive max_rows-sized column chunks from l."""
620 if row_first:
622 if row_first:
621 ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
623 ncols = (len(l) // max_rows) + (len(l) % max_rows > 0)
622 for i in py3compat.xrange(ncols):
624 for i in range(ncols):
623 yield [l[j] for j in py3compat.xrange(i, len(l), ncols)]
625 yield [l[j] for j in range(i, len(l), ncols)]
624 else:
626 else:
625 for i in py3compat.xrange(0, len(l), max_rows):
627 for i in range(0, len(l), max_rows):
626 yield l[i:(i + max_rows)]
628 yield l[i:(i + max_rows)]
627
629
628
630
@@ -16,8 +16,6 b' Utilities for timing code execution.'
16
16
17 import time
17 import time
18
18
19 from .py3compat import xrange
20
21 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
22 # Code
20 # Code
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
@@ -89,7 +87,7 b' def timings_out(reps,func,*args,**kw):'
89 out = func(*args,**kw)
87 out = func(*args,**kw)
90 tot_time = clock()-start
88 tot_time = clock()-start
91 else:
89 else:
92 rng = xrange(reps-1) # the last time is executed separately to store output
90 rng = range(reps-1) # the last time is executed separately to store output
93 start = clock()
91 start = clock()
94 for dummy in rng: func(*args,**kw)
92 for dummy in rng: func(*args,**kw)
95 out = func(*args,**kw) # one last time
93 out = func(*args,**kw) # one last time
@@ -25,8 +25,7 b' else:'
25 filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding())
25 filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding())
26 lines = linecache.getlines(filename, module_globals=module_globals)
26 lines = linecache.getlines(filename, module_globals=module_globals)
27
27
28 # The bits we cache ourselves can be unicode.
28 if (not lines) or isinstance(lines[0], str):
29 if (not lines) or isinstance(lines[0], py3compat.unicode_type):
30 return lines
29 return lines
31
30
32 readline = openpy._list_readline(lines)
31 readline = openpy._list_readline(lines)
@@ -18,7 +18,6 b' import re'
18 import types
18 import types
19
19
20 from IPython.utils.dir2 import dir2
20 from IPython.utils.dir2 import dir2
21 from .py3compat import iteritems
22
21
23 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
22 def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
24 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
23 """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
@@ -83,7 +82,7 b' def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,'
83 reg = re.compile(pattern+"$")
82 reg = re.compile(pattern+"$")
84
83
85 # Check each one matches regex; shouldn't be hidden; of correct type.
84 # Check each one matches regex; shouldn't be hidden; of correct type.
86 return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \
85 return dict((key,obj) for key, obj in ns.items() if reg.match(key) \
87 and show_hidden(key, show_all) \
86 and show_hidden(key, show_all) \
88 and is_type(obj, type_pattern) )
87 and is_type(obj, type_pattern) )
89
88
@@ -103,10 +102,10 b' def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all='
103 type_pattern="all",
102 type_pattern="all",
104 ignore_case=ignore_case, show_all=show_all)
103 ignore_case=ignore_case, show_all=show_all)
105 results = {}
104 results = {}
106 for name, obj in iteritems(filtered):
105 for name, obj in filtered.items():
107 ns = list_namespace(dict_dir(obj), type_pattern,
106 ns = list_namespace(dict_dir(obj), type_pattern,
108 ".".join(pattern_list[1:]),
107 ".".join(pattern_list[1:]),
109 ignore_case=ignore_case, show_all=show_all)
108 ignore_case=ignore_case, show_all=show_all)
110 for inner_name, inner_obj in iteritems(ns):
109 for inner_name, inner_obj in ns.items():
111 results["%s.%s"%(name,inner_name)] = inner_obj
110 results["%s.%s"%(name,inner_name)] = inner_obj
112 return results
111 return results
General Comments 0
You need to be logged in to leave comments. Login now