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