From 748d7071a25a4b9590c6bea7b66fdda64b037bd0 2017-01-06 13:19:12 From: Thomas Kluyver Date: 2017-01-06 13:19:12 Subject: [PATCH] Merge pull request #10105 from srinivasreddy/dead_code Convert iteritems() to items() --- diff --git a/IPython/core/alias.py b/IPython/core/alias.py index 28a9ccb..ee377d5 100644 --- a/IPython/core/alias.py +++ b/IPython/core/alias.py @@ -27,7 +27,6 @@ import sys from traitlets.config.configurable import Configurable from IPython.core.error import UsageError -from IPython.utils.py3compat import string_types from traitlets import List, Instance from logging import error @@ -148,7 +147,7 @@ class Alias(object): raise InvalidAliasError("The name %s can't be aliased " "because it is another magic command." % self.name) - if not (isinstance(self.cmd, string_types)): + if not (isinstance(self.cmd, str)): raise InvalidAliasError("An alias command must be a string, " "got: %r" % self.cmd) diff --git a/IPython/core/application.py b/IPython/core/application.py index 1801627..d6ad998 100644 --- a/IPython/core/application.py +++ b/IPython/core/application.py @@ -126,7 +126,7 @@ class BaseIPythonApplication(Application): config_file_paths = List(Unicode()) @default('config_file_paths') def _config_file_paths_default(self): - return [py3compat.getcwd()] + return [os.getcwd()] extra_config_file = Unicode( help="""Path to an extra config file to load. @@ -215,7 +215,7 @@ class BaseIPythonApplication(Application): super(BaseIPythonApplication, self).__init__(**kwargs) # ensure current working directory exists try: - py3compat.getcwd() + os.getcwd() except: # exit if cwd doesn't exist self.log.error("Current working directory doesn't exist.") diff --git a/IPython/core/builtin_trap.py b/IPython/core/builtin_trap.py index b3c9fdf..b9d4e95 100644 --- a/IPython/core/builtin_trap.py +++ b/IPython/core/builtin_trap.py @@ -20,7 +20,7 @@ Authors: from traitlets.config.configurable import Configurable -from IPython.utils.py3compat import builtin_mod, iteritems +from IPython.utils.py3compat import builtin_mod from traitlets import Instance #----------------------------------------------------------------------------- @@ -90,14 +90,14 @@ class BuiltinTrap(Configurable): """Store ipython references in the __builtin__ namespace.""" add_builtin = self.add_builtin - for name, func in iteritems(self.auto_builtins): + for name, func in self.auto_builtins.items(): add_builtin(name, func) def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin - for key, val in iteritems(self._orig_builtins): + for key, val in self._orig_builtins.items(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False diff --git a/IPython/core/completer.py b/IPython/core/completer.py index cc822c1..3e2ab79 100644 --- a/IPython/core/completer.py +++ b/IPython/core/completer.py @@ -35,7 +35,7 @@ from IPython.utils import generics from IPython.utils.decorators import undoc from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.process import arg_split -from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2 +from IPython.utils.py3compat import builtin_mod, PY3, cast_unicode_py2 from traitlets import Bool, Enum, observe from functools import wraps @@ -423,14 +423,14 @@ def get__all__entries(obj): except: return [] - return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)] + return [cast_unicode_py2(w) for w in words if isinstance(w, str)] def match_dict_keys(keys, prefix, delims): """Used by dict_key_matches, matching the prefix to a list of keys""" if not prefix: return None, 0, [repr(k) for k in keys - if isinstance(k, (string_types, bytes))] + if isinstance(k, (str, bytes))] quote_match = re.search('["\']', prefix) quote = quote_match.group() try: diff --git a/IPython/core/completerlib.py b/IPython/core/completerlib.py index ba44e1e..5aa3686 100644 --- a/IPython/core/completerlib.py +++ b/IPython/core/completerlib.py @@ -33,7 +33,6 @@ from zipimport import zipimporter from IPython.core.completer import expand_user, compress_user from IPython.core.error import TryNext from IPython.utils._process_common import arg_split -from IPython.utils.py3compat import string_types # FIXME: this should be pulled in with the right call via the component system from IPython import get_ipython @@ -164,7 +163,7 @@ def try_import(mod, only_modules=False): completions.extend(getattr(m, '__all__', [])) if m_is_init: completions.extend(module_list(os.path.dirname(m.__file__))) - completions = {c for c in completions if isinstance(c, string_types)} + completions = {c for c in completions if isinstance(c, str)} completions.discard('__init__') return list(completions) @@ -188,7 +187,7 @@ def quick_completer(cmd, completions): [d:\ipython]|3> foo ba """ - if isinstance(completions, string_types): + if isinstance(completions, str): completions = completions.split() def do_complete(self, event): diff --git a/IPython/core/crashhandler.py b/IPython/core/crashhandler.py index c85c766..a6a74e8 100644 --- a/IPython/core/crashhandler.py +++ b/IPython/core/crashhandler.py @@ -27,7 +27,7 @@ from pprint import pformat from IPython.core import ultratb from IPython.core.release import author_email from IPython.utils.sysinfo import sys_info -from IPython.utils.py3compat import input, getcwd +from IPython.utils.py3compat import input #----------------------------------------------------------------------------- # Code @@ -139,9 +139,9 @@ class CrashHandler(object): try: rptdir = self.app.ipython_dir except: - rptdir = getcwd() + rptdir = os.getcwd() if rptdir is None or not os.path.isdir(rptdir): - rptdir = getcwd() + rptdir = os.getcwd() report_name = os.path.join(rptdir,self.crash_report_fname) # write the report filename into the instance dict so it can get # properly expanded out in the user message template diff --git a/IPython/core/display.py b/IPython/core/display.py index dbbff3e..c94b0b1 100644 --- a/IPython/core/display.py +++ b/IPython/core/display.py @@ -18,8 +18,7 @@ import struct import sys import warnings -from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, - unicode_type) +from IPython.utils.py3compat import cast_bytes_py2, cast_unicode from IPython.testing.skipdoctest import skip_doctest __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', @@ -481,7 +480,7 @@ class DisplayObject(object): filename : unicode Path to a local file to load the data from. """ - if data is not None and isinstance(data, string_types): + if data is not None and isinstance(data, str): if data.startswith('http') and url is None: url = data filename = None @@ -493,7 +492,7 @@ class DisplayObject(object): self.data = data self.url = url - self.filename = None if filename is None else unicode_type(filename) + self.filename = filename self.reload() self._check_data() @@ -539,7 +538,7 @@ class DisplayObject(object): class TextDisplayObject(DisplayObject): """Validate that display data is text""" def _check_data(self): - if self.data is not None and not isinstance(self.data, string_types): + if self.data is not None and not isinstance(self.data, str): raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) class Pretty(TextDisplayObject): @@ -657,7 +656,7 @@ class JSON(DisplayObject): @data.setter def data(self, data): - if isinstance(data, string_types): + if isinstance(data, str): warnings.warn("JSON expects JSONable dict or list, not JSON strings") data = json.loads(data) self._data = data @@ -715,11 +714,11 @@ class Javascript(TextDisplayObject): The full URLs of the css files should be given. A single css URL can also be given as a string. """ - if isinstance(lib, string_types): + if isinstance(lib, str): lib = [lib] elif lib is None: lib = [] - if isinstance(css, string_types): + if isinstance(css, str): css = [css] elif css is None: css = [] @@ -848,7 +847,7 @@ class Image(DisplayObject): ext = self._find_ext(url) elif data is None: raise ValueError("No image data found. Expecting filename, url, or data.") - elif isinstance(data, string_types) and ( + elif isinstance(data, str) and ( data.startswith('http') or _safe_exists(data) ): ext = self._find_ext(data) @@ -877,7 +876,7 @@ class Image(DisplayObject): # jpg->jpeg format = self._FMT_JPEG - self.format = unicode_type(format).lower() + self.format = format.lower() self.embed = embed if embed is not None else (url is None) if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: @@ -954,7 +953,7 @@ class Image(DisplayObject): return self._data_and_metadata() def _find_ext(self, s): - return unicode_type(s.split('.')[-1].lower()) + return s.split('.')[-1].lower() class Video(DisplayObject): @@ -999,7 +998,7 @@ class Video(DisplayObject): Video('path/to/video.mp4', embed=True) Video(b'raw-videodata', embed=True) """ - if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')): + if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): url = data data = None elif os.path.exists(data): @@ -1038,7 +1037,7 @@ class Video(DisplayObject): video = f.read() else: video = self.data - if isinstance(video, unicode_type): + if isinstance(video, str): # unicode input is already b64-encoded b64_video = video else: diff --git a/IPython/core/formatters.py b/IPython/core/formatters.py index adef488..28f61e2 100644 --- a/IPython/core/formatters.py +++ b/IPython/core/formatters.py @@ -29,7 +29,7 @@ from traitlets import ( default, observe, ) from IPython.utils.py3compat import ( - with_metaclass, string_types, unicode_type, + with_metaclass ) @@ -276,7 +276,7 @@ class BaseFormatter(Configurable): """ format_type = Unicode('text/plain') - _return_type = string_types + _return_type = str enabled = Bool(True).tag(config=True) @@ -376,7 +376,7 @@ class BaseFormatter(Configurable): ------ KeyError if the type has not been registered. """ - if isinstance(typ, string_types): + if isinstance(typ, str): typ_key = tuple(typ.rsplit('.',1)) if typ_key not in self.deferred_printers: # We may have it cached in the type map. We will have to @@ -419,7 +419,7 @@ class BaseFormatter(Configurable): this will be the previous value (to enable restoring later). """ # if string given, interpret as 'pkg.module.class_name' - if isinstance(typ, string_types): + if isinstance(typ, str): type_module, type_name = typ.rsplit('.', 1) return self.for_type_by_name(type_module, type_name, func) @@ -491,7 +491,7 @@ class BaseFormatter(Configurable): KeyError if the type is not registered and default is not specified. """ - if isinstance(typ, string_types): + if isinstance(typ, str): typ_key = tuple(typ.rsplit('.',1)) if typ_key not in self.deferred_printers: # We may have it cached in the type map. We will have to @@ -737,7 +737,7 @@ class PNGFormatter(BaseFormatter): print_method = ObjectName('_repr_png_') - _return_type = (bytes, unicode_type) + _return_type = (bytes, str) class JPEGFormatter(BaseFormatter): @@ -755,7 +755,7 @@ class JPEGFormatter(BaseFormatter): print_method = ObjectName('_repr_jpeg_') - _return_type = (bytes, unicode_type) + _return_type = (bytes, str) class LatexFormatter(BaseFormatter): @@ -804,7 +804,7 @@ class JSONFormatter(BaseFormatter): r, md = r # handle deprecated JSON-as-string form from IPython < 3 - if isinstance(r, string_types): + if isinstance(r, str): warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", FormatterWarning) r = json.loads(r) @@ -846,7 +846,7 @@ class PDFFormatter(BaseFormatter): print_method = ObjectName('_repr_pdf_') - _return_type = (bytes, unicode_type) + _return_type = (bytes, str) class IPythonDisplayFormatter(BaseFormatter): """A Formatter for objects that know how to display themselves. diff --git a/IPython/core/history.py b/IPython/core/history.py index 58d20ec..16efbcd 100644 --- a/IPython/core/history.py +++ b/IPython/core/history.py @@ -487,7 +487,7 @@ class HistoryManager(HistoryAccessor): @default('dir_hist') def _dir_hist_default(self): try: - return [py3compat.getcwd()] + return [os.getcwd()] except OSError: return [] @@ -593,7 +593,7 @@ class HistoryManager(HistoryAccessor): optionally open a new session.""" self.output_hist.clear() # The directory history can't be completely empty - self.dir_hist[:] = [py3compat.getcwd()] + self.dir_hist[:] = [os.getcwd()] if new_session: if self.session_number: diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index cce24de..970ef65 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -67,8 +67,7 @@ from IPython.utils.ipstruct import Struct from IPython.paths import get_ipython_dir from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists from IPython.utils.process import system, getoutput -from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, - with_metaclass, iteritems) +from IPython.utils.py3compat import builtin_mod, with_metaclass from IPython.utils.strdispatch import StrDispatch from IPython.utils.syspathcontext import prepended_to_syspath from IPython.utils.text import format_screen, LSString, SList, DollarFormatter @@ -550,7 +549,7 @@ class InteractiveShell(SingletonConfigurable): # keep track of where we started running (mainly for crash post-mortem) # This is not being used anywhere currently. - self.starting_dir = py3compat.getcwd() + self.starting_dir = os.getcwd() # Indentation management self.indent_current_nsp = 0 @@ -733,7 +732,7 @@ class InteractiveShell(SingletonConfigurable): def restore_sys_module_state(self): """Restore the state of the sys module.""" try: - for k, v in iteritems(self._orig_sys_module_state): + for k, v in self._orig_sys_module_state.items(): setattr(sys, k, v) except AttributeError: pass @@ -1255,7 +1254,7 @@ class InteractiveShell(SingletonConfigurable): # Also check in output history ns_refs.append(self.history_manager.output_hist) for ns in ns_refs: - to_delete = [n for n, o in iteritems(ns) if o is obj] + to_delete = [n for n, o in ns.items() if o is obj] for name in to_delete: del ns[name] @@ -1307,8 +1306,8 @@ class InteractiveShell(SingletonConfigurable): # We need a dict of name/value pairs to do namespace updates. if isinstance(variables, dict): vdict = variables - elif isinstance(variables, string_types+(list, tuple)): - if isinstance(variables, string_types): + elif isinstance(variables, (str, list, tuple)): + if isinstance(variables, str): vlist = variables.split() else: vlist = variables @@ -1347,7 +1346,7 @@ class InteractiveShell(SingletonConfigurable): variables : dict A dictionary mapping object names (as strings) to the objects. """ - for name, obj in iteritems(variables): + for name, obj in variables.items(): if name in self.user_ns and self.user_ns[name] is obj: del self.user_ns[name] self.user_ns_hidden.pop(name, None) @@ -1651,14 +1650,14 @@ class InteractiveShell(SingletonConfigurable): msg = "CustomTB must return list of strings, not %r" % stb if stb is None: return [] - elif isinstance(stb, string_types): + elif isinstance(stb, str): return [stb] elif not isinstance(stb, list): raise TypeError(msg) # it's a list for line in stb: # check every element - if not isinstance(line, string_types): + if not isinstance(line, str): raise TypeError(msg) return stb @@ -2154,7 +2153,7 @@ class InteractiveShell(SingletonConfigurable): from IPython.core import macro - if isinstance(themacro, string_types): + if isinstance(themacro, str): themacro = macro.Macro(themacro) if not isinstance(themacro, macro.Macro): raise ValueError('A macro must be a string or a Macro instance.') @@ -2203,14 +2202,12 @@ class InteractiveShell(SingletonConfigurable): with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) - cmd = py3compat.unicode_to_str(cmd) try: ec = os.system(cmd) except KeyboardInterrupt: print('\n' + self.get_exception_only(), file=sys.stderr) ec = -2 else: - cmd = py3compat.unicode_to_str(cmd) # For posix the result of the subprocess.call() below is an exit # code, which by convention is zero for success, positive for # program failure. Exit codes above 128 are reserved for signals, @@ -2343,7 +2340,7 @@ class InteractiveShell(SingletonConfigurable): exc_info = { u'status' : 'error', u'traceback' : stb, - u'ename' : unicode_type(etype.__name__), + u'ename' : etype.__name__, u'evalue' : py3compat.safe_unicode(evalue), } @@ -2382,7 +2379,7 @@ class InteractiveShell(SingletonConfigurable): user_ns = self.user_ns global_ns = self.user_global_ns - for key, expr in iteritems(expressions): + for key, expr in expressions.items(): try: value = self._format_user_obj(eval(expr, global_ns, user_ns)) except: @@ -3165,7 +3162,7 @@ class InteractiveShell(SingletonConfigurable): raise ValueError(("'%s' was not found in history, as a file, url, " "nor in the user namespace.") % target) - if isinstance(codeobj, string_types): + if isinstance(codeobj, str): return codeobj elif isinstance(codeobj, Macro): return codeobj.value diff --git a/IPython/core/logger.py b/IPython/core/logger.py index 091da50..e3cb233 100644 --- a/IPython/core/logger.py +++ b/IPython/core/logger.py @@ -18,7 +18,6 @@ import io import os import time -from IPython.utils.py3compat import str_to_unicode #**************************************************************************** # FIXME: This class isn't a mixin anymore, but it still needs attributes from @@ -193,8 +192,7 @@ which already exists. But you must first start the logging process with write = self.logfile.write if kind=='input': if self.timestamp: - write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n', - time.localtime()))) + write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', time.localtime())) write(data) elif kind=='output' and self.log_output: odata = u'\n'.join([u'#[Out]# %s' % s diff --git a/IPython/core/macro.py b/IPython/core/macro.py index 9032706..efc2968 100644 --- a/IPython/core/macro.py +++ b/IPython/core/macro.py @@ -37,7 +37,7 @@ class Macro(object): self.value = code + '\n' def __str__(self): - return py3compat.unicode_to_str(self.value) + return self.value def __unicode__(self): return self.value @@ -52,6 +52,6 @@ class Macro(object): def __add__(self, other): if isinstance(other, Macro): return Macro(self.value + other.value) - elif isinstance(other, py3compat.string_types): + elif isinstance(other, str): return Macro(self.value + other) raise TypeError diff --git a/IPython/core/magic.py b/IPython/core/magic.py index e139bed..132e958 100644 --- a/IPython/core/magic.py +++ b/IPython/core/magic.py @@ -24,7 +24,6 @@ from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 from decorator import decorator from IPython.utils.ipstruct import Struct from IPython.utils.process import arg_split -from IPython.utils.py3compat import string_types, iteritems from IPython.utils.text import dedent from traitlets import Bool, Dict, Instance, observe from logging import error @@ -192,7 +191,7 @@ def _method_magic_marker(magic_kind): name = func.__name__ retval = decorator(call, func) record_magic(magics, magic_kind, name, name) - elif isinstance(arg, string_types): + elif isinstance(arg, str): # Decorator called with arguments (@foo('bar')) name = arg def mark(func, *a, **kw): @@ -237,7 +236,7 @@ def _function_magic_marker(magic_kind): name = func.__name__ ip.register_magic_function(func, magic_kind, name) retval = decorator(call, func) - elif isinstance(arg, string_types): + elif isinstance(arg, str): # Decorator called with arguments (@foo('bar')) name = arg def mark(func, *a, **kw): @@ -344,7 +343,7 @@ class MagicsManager(Configurable): docs = {} for m_type in self.magics: m_docs = {} - for m_name, m_func in iteritems(self.magics[m_type]): + for m_name, m_func in self.magics[m_type].items(): if m_func.__doc__: if brief: m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] @@ -510,8 +509,8 @@ class Magics(Configurable): for mtype in magic_kinds: tab = self.magics[mtype] = {} cls_tab = class_magics[mtype] - for magic_name, meth_name in iteritems(cls_tab): - if isinstance(meth_name, string_types): + for magic_name, meth_name in cls_tab.items(): + if isinstance(meth_name, str): # it's a method name, grab it tab[magic_name] = getattr(self, meth_name) else: diff --git a/IPython/core/magics/basic.py b/IPython/core/magics/basic.py index c2427c9..475ddf8 100644 --- a/IPython/core/magics/basic.py +++ b/IPython/core/magics/basic.py @@ -12,7 +12,6 @@ from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes from IPython.utils.text import format_screen, dedent, indent from IPython.testing.skipdoctest import skip_doctest from IPython.utils.ipstruct import Struct -from IPython.utils.py3compat import unicode_type from warnings import warn from logging import error @@ -550,7 +549,7 @@ Currently the magic system has the following functions:""", help=argparse.SUPPRESS ) @magic_arguments.argument( - 'filename', type=unicode_type, + 'filename', type=str, help='Notebook name or filename' ) @line_magic diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py index 6439df7..804e1ea 100644 --- a/IPython/core/magics/code.py +++ b/IPython/core/magics/code.py @@ -28,7 +28,6 @@ from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.oinspect import find_file, find_source_lines from IPython.testing.skipdoctest import skip_doctest from IPython.utils import py3compat -from IPython.utils.py3compat import string_types from IPython.utils.contexts import preserve_keys from IPython.utils.path import get_py_filename from warnings import warn @@ -443,7 +442,7 @@ class CodeMagics(Magics): #print '*** args',args,'type',type(args) # dbg data = eval(args, shell.user_ns) - if not isinstance(data, string_types): + if not isinstance(data, str): raise DataIsObject except (NameError,SyntaxError): diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index ab62d8e..7279462 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -36,7 +36,7 @@ from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, line_cell_magic, on_off, needs_local_scope) from IPython.testing.skipdoctest import skip_doctest from IPython.utils import py3compat -from IPython.utils.py3compat import builtin_mod, iteritems, PY3 +from IPython.utils.py3compat import builtin_mod, PY3 from IPython.utils.contexts import preserve_keys from IPython.utils.capture import capture_output from IPython.utils.ipstruct import Struct @@ -1279,8 +1279,7 @@ python-profiler package from non-free.""") """ opts,args = self.parse_options(parameter_s,'rq',mode='list') if not args: # List existing macros - return sorted(k for k,v in iteritems(self.shell.user_ns) if\ - isinstance(v, Macro)) + return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)) if len(args) == 1: raise UsageError( "%macro insufficient args; usage '%macro name n1-n2 n3-4...") diff --git a/IPython/core/magics/logging.py b/IPython/core/magics/logging.py index 90214ab..9683c3f 100644 --- a/IPython/core/magics/logging.py +++ b/IPython/core/magics/logging.py @@ -19,7 +19,6 @@ import sys # Our own packages from IPython.core.magic import Magics, magics_class, line_magic from warnings import warn -from IPython.utils.py3compat import str_to_unicode #----------------------------------------------------------------------------- # Magic implementation classes @@ -138,7 +137,7 @@ class LoggingMagics(Magics): for n in range(1,len(input_hist)-1): log_write(input_hist[n].rstrip() + u'\n') if n in output_hist: - log_write(str_to_unicode(repr(output_hist[n])),'output') + log_write(repr(output_hist[n]),'output') else: logger.log_write(u'\n'.join(input_hist[1:])) logger.log_write(u'\n') diff --git a/IPython/core/magics/namespace.py b/IPython/core/magics/namespace.py index 68442f9..343db92 100644 --- a/IPython/core/magics/namespace.py +++ b/IPython/core/magics/namespace.py @@ -25,7 +25,6 @@ from IPython.testing.skipdoctest import skip_doctest from IPython.utils.encoding import DEFAULT_ENCODING from IPython.utils.openpy import read_py_file from IPython.utils.path import get_py_filename -from IPython.utils.py3compat import unicode_type #----------------------------------------------------------------------------- # Magic implementation classes @@ -460,8 +459,8 @@ class NamespaceMagics(Magics): try: vstr = str(var) except UnicodeEncodeError: - vstr = unicode_type(var).encode(DEFAULT_ENCODING, - 'backslashreplace') + vstr = var.encode(DEFAULT_ENCODING, + 'backslashreplace') except: vstr = "" % id(var) vstr = vstr.replace('\n', '\\n') diff --git a/IPython/core/magics/osm.py b/IPython/core/magics/osm.py index 0d85a01..e1fbbad 100644 --- a/IPython/core/magics/osm.py +++ b/IPython/core/magics/osm.py @@ -35,7 +35,6 @@ from IPython.testing.skipdoctest import skip_doctest from IPython.utils.openpy import source_to_unicode from IPython.utils.process import abbrev_cwd from IPython.utils import py3compat -from IPython.utils.py3compat import unicode_type from IPython.utils.terminal import set_term_title #----------------------------------------------------------------------------- @@ -178,7 +177,7 @@ class OSMagics(Magics): winext += '|py' execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) - savedir = py3compat.getcwd() + savedir = os.getcwd() # Now walk the paths looking for executables to alias. try: @@ -240,7 +239,7 @@ class OSMagics(Magics): In [9]: pwd Out[9]: '/home/tsuser/sprint/ipython' """ - return py3compat.getcwd() + return os.getcwd() @skip_doctest @line_magic @@ -284,7 +283,7 @@ class OSMagics(Magics): /home/tsuser/parent/child """ - oldcwd = py3compat.getcwd() + oldcwd = os.getcwd() numcd = re.match(r'(-)(\d+)$',parameter_s) # jump in directory history by number if numcd: @@ -352,7 +351,7 @@ class OSMagics(Magics): except OSError: print(sys.exc_info()[1]) else: - cwd = py3compat.getcwd() + cwd = os.getcwd() dhist = self.shell.user_ns['_dh'] if oldcwd != cwd: dhist.append(cwd) @@ -362,7 +361,7 @@ class OSMagics(Magics): os.chdir(self.shell.home_dir) if hasattr(self.shell, 'term_title') and self.shell.term_title: set_term_title('IPython: ' + '~') - cwd = py3compat.getcwd() + cwd = os.getcwd() dhist = self.shell.user_ns['_dh'] if oldcwd != cwd: @@ -437,7 +436,7 @@ class OSMagics(Magics): dir_s = self.shell.dir_stack tgt = os.path.expanduser(parameter_s) - cwd = py3compat.getcwd().replace(self.shell.home_dir,'~') + cwd = os.getcwd().replace(self.shell.home_dir,'~') if tgt: self.cd(parameter_s) dir_s.insert(0,cwd) @@ -725,7 +724,7 @@ class OSMagics(Magics): if not args: raise UsageError("%bookmark: You must specify the bookmark name") elif len(args)==1: - bkms[args[0]] = py3compat.getcwd() + bkms[args[0]] = os.getcwd() elif len(args)==2: bkms[args[0]] = args[1] self.shell.db['bookmarks'] = bkms @@ -764,7 +763,7 @@ class OSMagics(Magics): 'The file will be created if it does not exist.' ) @magic_arguments.argument( - 'filename', type=unicode_type, + 'filename', type=str, help='file to write' ) @cell_magic diff --git a/IPython/core/oinspect.py b/IPython/core/oinspect.py index 4959742..fbe37bf 100644 --- a/IPython/core/oinspect.py +++ b/IPython/core/oinspect.py @@ -35,7 +35,7 @@ from IPython.utils.path import compress_user from IPython.utils.text import indent from IPython.utils.wildcard import list_namespace from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable -from IPython.utils.py3compat import cast_unicode, string_types, PY3 +from IPython.utils.py3compat import cast_unicode, PY3 from IPython.utils.colorable import Colorable from IPython.utils.decorators import undoc @@ -124,7 +124,7 @@ def getdoc(obj): pass else: # if we get extra info, we add it to the normal docstring. - if isinstance(ds, string_types): + if isinstance(ds, str): return inspect.cleandoc(ds) try: docstr = inspect.getdoc(obj) diff --git a/IPython/core/profileapp.py b/IPython/core/profileapp.py index ee78ab6..f43962f 100644 --- a/IPython/core/profileapp.py +++ b/IPython/core/profileapp.py @@ -180,10 +180,10 @@ class ProfileList(Application): print("Available profiles in %s:" % self.ipython_dir) self._print_profiles(profiles) - profiles = list_profiles_in(py3compat.getcwd()) + profiles = list_profiles_in(os.getcwd()) if profiles: print() - print("Available profiles in current directory (%s):" % py3compat.getcwd()) + print("Available profiles in current directory (%s):" % os.getcwd()) self._print_profiles(profiles) print() diff --git a/IPython/core/profiledir.py b/IPython/core/profiledir.py index 9c9e99c..6c0dc7b 100644 --- a/IPython/core/profiledir.py +++ b/IPython/core/profiledir.py @@ -187,7 +187,7 @@ class ProfileDir(LoggingConfigurable): is not found, a :class:`ProfileDirError` exception will be raised. The search path algorithm is: - 1. ``py3compat.getcwd()`` + 1. ``os.getcwd()`` 2. ``ipython_dir`` Parameters @@ -199,7 +199,7 @@ class ProfileDir(LoggingConfigurable): will be "profile_". """ dirname = u'profile_' + name - paths = [py3compat.getcwd(), ipython_dir] + paths = [os.getcwd(), ipython_dir] for p in paths: profile_dir = os.path.join(p, dirname) if os.path.isdir(profile_dir): diff --git a/IPython/core/prompts.py b/IPython/core/prompts.py index 7802bc5..ec7f911 100644 --- a/IPython/core/prompts.py +++ b/IPython/core/prompts.py @@ -18,9 +18,6 @@ class LazyEvaluate(object): def __str__(self): return str(self()) - - def __unicode__(self): - return py3compat.unicode_type(self()) - + def __format__(self, format_spec): return format(self(), format_spec) diff --git a/IPython/core/pylabtools.py b/IPython/core/pylabtools.py index 33f2a03..30ca16b 100644 --- a/IPython/core/pylabtools.py +++ b/IPython/core/pylabtools.py @@ -217,7 +217,7 @@ def select_figure_formats(shell, formats, **kwargs): jpg_formatter = shell.display_formatter.formatters['image/jpeg'] pdf_formatter = shell.display_formatter.formatters['application/pdf'] - if isinstance(formats, py3compat.string_types): + if isinstance(formats, str): formats = {formats} # cast in case of list / tuple formats = set(formats) diff --git a/IPython/core/tests/test_application.py b/IPython/core/tests/test_application.py index fb7724f..34cab5b 100644 --- a/IPython/core/tests/test_application.py +++ b/IPython/core/tests/test_application.py @@ -19,9 +19,9 @@ def test_unicode_cwd(): """Check that IPython starts with non-ascii characters in the path.""" wd = tempfile.mkdtemp(suffix=u"€") - old_wd = py3compat.getcwd() + old_wd = os.getcwd() os.chdir(wd) - #raise Exception(repr(py3compat.getcwd())) + #raise Exception(repr(os.getcwd())) try: app = BaseIPythonApplication() # The lines below are copied from Application.initialize() @@ -42,7 +42,7 @@ def test_unicode_ipdir(): old_ipdir1 = os.environ.pop("IPYTHONDIR", None) old_ipdir2 = os.environ.pop("IPYTHON_DIR", None) - os.environ["IPYTHONDIR"] = py3compat.unicode_to_str(ipdir, "utf-8") + os.environ["IPYTHONDIR"] = ipdir try: app = BaseIPythonApplication() # The lines below are copied from Application.initialize() diff --git a/IPython/core/tests/test_completer.py b/IPython/core/tests/test_completer.py index e406f3a..cd67594 100644 --- a/IPython/core/tests/test_completer.py +++ b/IPython/core/tests/test_completer.py @@ -18,7 +18,6 @@ from IPython.core import completer from IPython.external.decorators import knownfailureif from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory from IPython.utils.generics import complete_object -from IPython.utils.py3compat import string_types, unicode_type from IPython.testing import decorators as dec #----------------------------------------------------------------------------- @@ -102,7 +101,7 @@ def test_line_split(): check_line_split(sp, t) # Ensure splitting works OK with unicode by re-running the tests with # all inputs turned into unicode - check_line_split(sp, [ map(unicode_type, p) for p in t] ) + check_line_split(sp, [ map(str, p) for p in t] ) def test_custom_completion_error(): @@ -123,13 +122,13 @@ def test_unicode_completions(): # Some strings that trigger different types of completion. Check them both # in str and unicode forms s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/'] - for t in s + list(map(unicode_type, s)): + for t in s + list(map(str, s)): # We don't need to check exact completion values (they may change # depending on the state of the namespace, but at least no exceptions # should be thrown and the return value should be a pair of text, list # values. text, matches = ip.complete(t) - nt.assert_true(isinstance(text, string_types)) + nt.assert_true(isinstance(text, str)) nt.assert_true(isinstance(matches, list)) def test_latex_completions(): diff --git a/IPython/core/tests/test_completerlib.py b/IPython/core/tests/test_completerlib.py index 82d246b..97b561d 100644 --- a/IPython/core/tests/test_completerlib.py +++ b/IPython/core/tests/test_completerlib.py @@ -41,7 +41,7 @@ class Test_magic_run_completer(unittest.TestCase): for d in self.dirs: os.mkdir(join(self.BASETESTDIR, d)) - self.oldpath = py3compat.getcwd() + self.oldpath = os.getcwd() os.chdir(self.BASETESTDIR) def tearDown(self): @@ -94,7 +94,7 @@ class Test_magic_run_completer_nonascii(unittest.TestCase): for fil in [u"aaø.py", u"a.py", u"b.py"]: with open(join(self.BASETESTDIR, fil), "w") as sfile: sfile.write("pass\n") - self.oldpath = py3compat.getcwd() + self.oldpath = os.getcwd() os.chdir(self.BASETESTDIR) def tearDown(self): @@ -157,6 +157,6 @@ def test_bad_module_all(): results = module_completion('from bad_all import ') nt.assert_in('puppies', results) for r in results: - nt.assert_is_instance(r, py3compat.string_types) + nt.assert_is_instance(r, str) finally: sys.path.remove(testsdir) diff --git a/IPython/core/tests/test_inputsplitter.py b/IPython/core/tests/test_inputsplitter.py index 17a7e37..90dd911 100644 --- a/IPython/core/tests/test_inputsplitter.py +++ b/IPython/core/tests/test_inputsplitter.py @@ -15,7 +15,7 @@ from IPython.core.inputtransformer import InputTransformer from IPython.core.tests.test_inputtransformer import syntax, syntax_ml from IPython.testing import tools as tt from IPython.utils import py3compat -from IPython.utils.py3compat import string_types, input +from IPython.utils.py3compat import input #----------------------------------------------------------------------------- # Semi-complete examples (also used as tests) @@ -100,7 +100,7 @@ def test_remove_comments(): def test_get_input_encoding(): encoding = isp.get_input_encoding() - nt.assert_true(isinstance(encoding, string_types)) + nt.assert_true(isinstance(encoding, str)) # simple-minded check that at least encoding a simple string works with the # encoding we got. nt.assert_equal(u'test'.encode(encoding), b'test') diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py index a350316..9236b7a 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -32,7 +32,7 @@ from IPython.testing.decorators import ( from IPython.testing import tools as tt from IPython.utils.process import find_cmd from IPython.utils import py3compat -from IPython.utils.py3compat import unicode_type, PY3 +from IPython.utils.py3compat import PY3 if PY3: from io import StringIO @@ -473,7 +473,7 @@ class InteractiveShellTestCase(unittest.TestCase): def test_inspect_text(self): ip.run_cell('a = 5') text = ip.object_inspect_text('a') - self.assertIsInstance(text, unicode_type) + self.assertIsInstance(text, str) class TestSafeExecfileNonAsciiPath(unittest.TestCase): @@ -485,7 +485,7 @@ class TestSafeExecfileNonAsciiPath(unittest.TestCase): os.mkdir(self.TESTDIR) with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile: sfile.write("pass\n") - self.oldpath = py3compat.getcwd() + self.oldpath = os.getcwd() os.chdir(self.TESTDIR) self.fname = u"åäötestscript.py" diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py index 6fea789..71c9692 100644 --- a/IPython/core/tests/test_magic.py +++ b/IPython/core/tests/test_magic.py @@ -393,9 +393,9 @@ def test_parse_options(): def test_dirops(): """Test various directory handling operations.""" - # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/') - curpath = py3compat.getcwd - startdir = py3compat.getcwd() + # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/') + curpath = os.getcwd + startdir = os.getcwd() ipdir = os.path.realpath(_ip.ipython_dir) try: _ip.magic('cd "%s"' % ipdir) diff --git a/IPython/core/tests/test_profile.py b/IPython/core/tests/test_profile.py index 79e3d4b..80599d2 100644 --- a/IPython/core/tests/test_profile.py +++ b/IPython/core/tests/test_profile.py @@ -121,7 +121,6 @@ def test_list_profiles_in(): # No need to remove these directories and files, as they will get nuked in # the module-level teardown. td = tempfile.mkdtemp(dir=TMP_TEST_DIR) - td = py3compat.str_to_unicode(td) for name in ('profile_foo', 'profile_hello', 'not_a_profile'): os.mkdir(os.path.join(td, name)) if dec.unicode_paths: @@ -161,4 +160,4 @@ def test_profile_create_ipython_dir(): assert os.path.exists(profile_dir) ipython_config = os.path.join(profile_dir, 'ipython_config.py') assert os.path.exists(ipython_config) - \ No newline at end of file + diff --git a/IPython/core/tests/test_prompts.py b/IPython/core/tests/test_prompts.py index 6595dab..4082b14 100644 --- a/IPython/core/tests/test_prompts.py +++ b/IPython/core/tests/test_prompts.py @@ -5,7 +5,6 @@ import unittest from IPython.core.prompts import LazyEvaluate from IPython.testing.globalipapp import get_ipython -from IPython.utils.py3compat import unicode_type ip = get_ipython() @@ -14,8 +13,7 @@ class PromptTests(unittest.TestCase): def test_lazy_eval_unicode(self): u = u'ünicødé' lz = LazyEvaluate(lambda : u) - # str(lz) would fail - self.assertEqual(unicode_type(lz), u) + self.assertEqual(str(lz), u) self.assertEqual(format(lz), u) def test_lazy_eval_nonascii_bytes(self): @@ -31,7 +29,6 @@ class PromptTests(unittest.TestCase): lz = LazyEvaluate(lambda : f) self.assertEqual(str(lz), str(f)) - self.assertEqual(unicode_type(lz), unicode_type(f)) self.assertEqual(format(lz), str(f)) self.assertEqual(format(lz, '.1'), '0.5') diff --git a/IPython/core/tests/test_run.py b/IPython/core/tests/test_run.py index f73d235..d684990 100644 --- a/IPython/core/tests/test_run.py +++ b/IPython/core/tests/test_run.py @@ -408,7 +408,7 @@ class TestMagicRunWithPackage(unittest.TestCase): self.value = int(random.random() * 10000) self.tempdir = TemporaryDirectory() - self.__orig_cwd = py3compat.getcwd() + self.__orig_cwd = os.getcwd() sys.path.insert(0, self.tempdir.name) self.writefile(os.path.join(package, '__init__.py'), '') diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py index df451e0..f7d4c76 100644 --- a/IPython/core/ultratb.py +++ b/IPython/core/ultratb.py @@ -1060,7 +1060,7 @@ class VerboseTB(TBTools): if (not py3compat.PY3) and type(evalue) is types.InstanceType: try: - names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)] + names = [w for w in dir(evalue) if isinstance(w, str)] except: # Every now and then, an object with funny internals blows up # when dir() is called on it. We do the best we can to report @@ -1429,7 +1429,7 @@ class SyntaxTB(ListTB): # be wrong (retrieved from an outdated cache). This replaces it with # the current value. if isinstance(value, SyntaxError) \ - and isinstance(value.filename, py3compat.string_types) \ + and isinstance(value.filename, str) \ and isinstance(value.lineno, int): linecache.checkcache(value.filename) newtext = ulinecache.getline(value.filename, value.lineno) diff --git a/IPython/extensions/storemagic.py b/IPython/extensions/storemagic.py index 32a3505..9a203ff 100644 --- a/IPython/extensions/storemagic.py +++ b/IPython/extensions/storemagic.py @@ -18,7 +18,6 @@ import inspect, os, sys, textwrap from IPython.core.error import UsageError from IPython.core.magic import Magics, magics_class, line_magic from traitlets import Bool -from IPython.utils.py3compat import string_types def restore_aliases(ip): @@ -178,7 +177,7 @@ class StoreMagics(Magics): obj.__class__.__name__, fnam)) - if not isinstance (obj, string_types): + if not isinstance (obj, str): from pprint import pprint pprint(obj, fil) else: diff --git a/IPython/lib/backgroundjobs.py b/IPython/lib/backgroundjobs.py index a3a02ab..1fc81d7 100644 --- a/IPython/lib/backgroundjobs.py +++ b/IPython/lib/backgroundjobs.py @@ -36,7 +36,6 @@ import threading from IPython import get_ipython from IPython.core.ultratb import AutoFormattedTB from logging import error -from IPython.utils.py3compat import string_types class BackgroundJobManager(object): @@ -171,7 +170,7 @@ class BackgroundJobManager(object): if callable(func_or_exp): kw = kwargs.get('kw',{}) job = BackgroundJobFunc(func_or_exp,*args,**kw) - elif isinstance(func_or_exp, string_types): + elif isinstance(func_or_exp, str): if not args: frame = sys._getframe(1) glob, loc = frame.f_globals, frame.f_locals diff --git a/IPython/lib/pretty.py b/IPython/lib/pretty.py index 3eaa0b3..83cf094 100644 --- a/IPython/lib/pretty.py +++ b/IPython/lib/pretty.py @@ -84,7 +84,7 @@ import re import datetime from collections import deque -from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types +from IPython.utils.py3compat import PY3, PYPY, cast_unicode from IPython.utils.encoding import get_stream_enc from io import StringIO @@ -679,13 +679,13 @@ def _type_pprint(obj, p, cycle): mod = _safe_getattr(obj, '__module__', None) try: name = obj.__qualname__ - if not isinstance(name, string_types): + if not isinstance(name, str): # This can happen if the type implements __qualname__ as a property # or other descriptor in Python 2. raise Exception("Try __name__") except Exception: name = obj.__name__ - if not isinstance(name, string_types): + if not isinstance(name, str): name = '' if mod in (None, '__builtin__', 'builtins', 'exceptions'): @@ -771,7 +771,6 @@ except AttributeError: # Python 3 _type_pprinters[slice] = _repr_pprint try: - _type_pprinters[xrange] = _repr_pprint _type_pprinters[long] = _repr_pprint _type_pprinters[unicode] = _repr_pprint except NameError: diff --git a/IPython/lib/tests/test_clipboard.py b/IPython/lib/tests/test_clipboard.py index c0d6ed9..f1050bf 100644 --- a/IPython/lib/tests/test_clipboard.py +++ b/IPython/lib/tests/test_clipboard.py @@ -3,7 +3,6 @@ import nose.tools as nt from IPython.core.error import TryNext from IPython.lib.clipboard import ClipboardEmpty from IPython.testing.decorators import skip_if_no_x11 -from IPython.utils.py3compat import unicode_type @skip_if_no_x11 def test_clipboard_get(): @@ -19,4 +18,4 @@ def test_clipboard_get(): # No clipboard access API available pass else: - nt.assert_is_instance(a, unicode_type) + nt.assert_is_instance(a, str) diff --git a/IPython/terminal/interactiveshell.py b/IPython/terminal/interactiveshell.py index 763761b..22e84c7 100644 --- a/IPython/terminal/interactiveshell.py +++ b/IPython/terminal/interactiveshell.py @@ -7,7 +7,7 @@ from warnings import warn from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC from IPython.utils import io -from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types +from IPython.utils.py3compat import PY3, cast_unicode_py2, input from IPython.utils.terminal import toggle_set_term_title, set_term_title from IPython.utils.process import abbrev_cwd from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union @@ -289,7 +289,7 @@ class TerminalInteractiveShell(InteractiveShell): else : raise ValueError('Got unknown colors: ', legacy) else : - if isinstance(name_or_cls, string_types): + if isinstance(name_or_cls, str): style_cls = get_style_by_name(name_or_cls) else: style_cls = name_or_cls diff --git a/IPython/terminal/magics.py b/IPython/terminal/magics.py index 474d9e6..4c773ef 100644 --- a/IPython/terminal/magics.py +++ b/IPython/terminal/magics.py @@ -26,7 +26,7 @@ def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): prompt = "" while True: try: - l = py3compat.str_to_unicode(l_input(prompt)) + l = l_input(prompt) if l == sentinel: return else: @@ -72,7 +72,7 @@ class TerminalMagics(Magics): # Sanity checks if b is None: raise UsageError('No previous pasted block available') - if not isinstance(b, py3compat.string_types): + if not isinstance(b, str): raise UsageError( "Variable 'pasted_block' is not a string, can't execute") diff --git a/IPython/testing/decorators.py b/IPython/testing/decorators.py index 45c26ea..5a1a46c 100644 --- a/IPython/testing/decorators.py +++ b/IPython/testing/decorators.py @@ -49,7 +49,7 @@ from .ipunittest import ipdoctest, ipdocstring from IPython.external.decorators import * # For onlyif_cmd_exists decorator -from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY +from IPython.utils.py3compat import which, PY2, PY3, PYPY #----------------------------------------------------------------------------- # Classes and functions @@ -131,7 +131,7 @@ def make_label_dec(label, ds=None): warnings.warn("The function `make_label_dec` is deprecated since IPython 4.0", DeprecationWarning, stacklevel=2) - if isinstance(label, string_types): + if isinstance(label, str): labels = [label] else: labels = label diff --git a/IPython/testing/plugin/ipdoctest.py b/IPython/testing/plugin/ipdoctest.py index 2d4dd9b..841ccdf 100644 --- a/IPython/testing/plugin/ipdoctest.py +++ b/IPython/testing/plugin/ipdoctest.py @@ -45,7 +45,7 @@ from nose.plugins import doctests, Plugin from nose.util import anyp, tolist # Our own imports -from IPython.utils.py3compat import builtin_mod, PY3, getcwd +from IPython.utils.py3compat import builtin_mod, PY3 if PY3: from io import StringIO @@ -259,7 +259,7 @@ class DocTestCase(doctests.DocTestCase): # Save our current directory and switch out to the one where the # test was originally created, in case another doctest did a # directory change. We'll restore this in the finally clause. - curdir = getcwd() + curdir = os.getcwd() #print 'runTest in dir:', self._ori_dir # dbg os.chdir(self._ori_dir) diff --git a/IPython/testing/tools.py b/IPython/testing/tools.py index 40cfde7..1779221 100644 --- a/IPython/testing/tools.py +++ b/IPython/testing/tools.py @@ -354,7 +354,7 @@ class AssertPrints(object): """ def __init__(self, s, channel='stdout', suppress=True): self.s = s - if isinstance(self.s, (py3compat.string_types, _re_type)): + if isinstance(self.s, (str, _re_type)): self.s = [self.s] self.channel = channel self.suppress = suppress diff --git a/IPython/utils/_process_common.py b/IPython/utils/_process_common.py index 9ede30d..fa2144c 100644 --- a/IPython/utils/_process_common.py +++ b/IPython/utils/_process_common.py @@ -71,7 +71,7 @@ def process_handler(cmd, callback, stderr=subprocess.PIPE): # On win32, close_fds can't be true when using pipes for stdin/out/err close_fds = sys.platform != 'win32' # Determine if cmd should be run with system shell. - shell = isinstance(cmd, py3compat.string_types) + shell = isinstance(cmd, str) # On POSIX systems run shell commands with user-preferred shell. executable = None if shell and os.name == 'posix' and 'SHELL' in os.environ: diff --git a/IPython/utils/_process_win32.py b/IPython/utils/_process_win32.py index 554cf9f..bfad1b5 100644 --- a/IPython/utils/_process_win32.py +++ b/IPython/utils/_process_win32.py @@ -53,7 +53,7 @@ class AvoidUNCPath(object): os.system(cmd) """ def __enter__(self): - self.path = py3compat.getcwd() + self.path = os.getcwd() self.is_unc_path = self.path.startswith(r"\\") if self.is_unc_path: # change to c drive (as cmd.exe cannot handle UNC addresses) diff --git a/IPython/utils/_process_win32_controller.py b/IPython/utils/_process_win32_controller.py index 85a342e..4fd2e3c 100644 --- a/IPython/utils/_process_win32_controller.py +++ b/IPython/utils/_process_win32_controller.py @@ -173,7 +173,7 @@ class AvoidUNCPath(object): os.system(cmd) """ def __enter__(self): - self.path = py3compat.getcwd() + self.path = os.getcwd() self.is_unc_path = self.path.startswith(r"\\") if self.is_unc_path: # change to c drive (as cmd.exe cannot handle UNC addresses) diff --git a/IPython/utils/data.py b/IPython/utils/data.py index 308a692..bf70cf8 100644 --- a/IPython/utils/data.py +++ b/IPython/utils/data.py @@ -9,7 +9,6 @@ # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- -from .py3compat import xrange def uniq_stable(elems): """uniq_stable(elems) -> list @@ -32,6 +31,6 @@ def flatten(seq): def chop(seq, size): """Chop a sequence into chunks of the given size.""" - return [seq[i:i+size] for i in xrange(0,len(seq),size)] + return [seq[i:i+size] for i in range(0,len(seq),size)] diff --git a/IPython/utils/dir2.py b/IPython/utils/dir2.py index f6f164f..50805e0 100644 --- a/IPython/utils/dir2.py +++ b/IPython/utils/dir2.py @@ -6,7 +6,6 @@ # Distributed under the terms of the Modified BSD License. import inspect -from .py3compat import string_types def safe_hasattr(obj, attr): @@ -44,7 +43,7 @@ def dir2(obj): # filter out non-string attributes which may be stuffed by dir() calls # and poor coding in third-party modules - words = [w for w in words if isinstance(w, string_types)] + words = [w for w in words if isinstance(w, str)] return sorted(words) diff --git a/IPython/utils/io.py b/IPython/utils/io.py index cf27dd1..dcbef22 100644 --- a/IPython/utils/io.py +++ b/IPython/utils/io.py @@ -17,7 +17,7 @@ from warnings import warn from IPython.utils.decorators import undoc from .capture import CapturedIO, capture_output -from .py3compat import string_types, input, PY3 +from .py3compat import input, PY3 @undoc class IOStream: @@ -63,7 +63,7 @@ class IOStream: def writelines(self, lines): warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead', DeprecationWarning, stacklevel=2) - if isinstance(lines, string_types): + if isinstance(lines, str): lines = [lines] for line in lines: self.write(line) diff --git a/IPython/utils/openpy.py b/IPython/utils/openpy.py index 1ec22a4..ad7e267 100644 --- a/IPython/utils/openpy.py +++ b/IPython/utils/openpy.py @@ -10,7 +10,6 @@ from io import TextIOWrapper, BytesIO import os.path import re -from .py3compat import unicode_type cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE) cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE) @@ -129,7 +128,7 @@ def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): txt can be either a bytes buffer or a string containing the source code. """ - if isinstance(txt, unicode_type): + if isinstance(txt, str): return txt if isinstance(txt, bytes): buffer = BytesIO(txt) diff --git a/IPython/utils/path.py b/IPython/utils/path.py index fa85081..9590eda 100644 --- a/IPython/utils/path.py +++ b/IPython/utils/path.py @@ -87,7 +87,6 @@ def unquote_filename(name, win32=(sys.platform=='win32')): def compress_user(path): """Reverse of :func:`os.path.expanduser` """ - path = py3compat.unicode_to_str(path, sys.getfilesystemencoding()) home = os.path.expanduser('~') if path.startswith(home): path = "~" + path[len(home):] @@ -154,11 +153,11 @@ def filefind(filename, path_dirs=None): if path_dirs is None: path_dirs = ("",) - elif isinstance(path_dirs, py3compat.string_types): + elif isinstance(path_dirs, str): path_dirs = (path_dirs,) for path in path_dirs: - if path == '.': path = py3compat.getcwd() + if path == '.': path = os.getcwd() testname = expand_path(os.path.join(path, filename)) if os.path.isfile(testname): return os.path.abspath(testname) diff --git a/IPython/utils/process.py b/IPython/utils/process.py index 169d3c3..77b2064 100644 --- a/IPython/utils/process.py +++ b/IPython/utils/process.py @@ -52,7 +52,7 @@ def find_cmd(cmd): def abbrev_cwd(): """ Return abbreviated version of cwd, e.g. d:mydir """ - cwd = py3compat.getcwd().replace('\\','/') + cwd = os.getcwd().replace('\\','/') drivepart = '' tail = cwd if sys.platform == 'win32': diff --git a/IPython/utils/terminal.py b/IPython/utils/terminal.py index 3bdcee3..4668994 100644 --- a/IPython/utils/terminal.py +++ b/IPython/utils/terminal.py @@ -93,7 +93,7 @@ elif sys.platform == 'win32': try: # Cannot be on network share when issuing system commands - curr = py3compat.getcwd() + curr = os.getcwd() os.chdir("C:") ret = os.system("title " + title) finally: diff --git a/IPython/utils/tests/test_path.py b/IPython/utils/tests/test_path.py index 966f3a8..cc48fe8 100644 --- a/IPython/utils/tests/test_path.py +++ b/IPython/utils/tests/test_path.py @@ -356,7 +356,7 @@ class TestShellGlob(object): @classmethod @contextmanager def in_tempdir(cls): - save = py3compat.getcwd() + save = os.getcwd() try: os.chdir(cls.tempdir.name) yield diff --git a/IPython/utils/text.py b/IPython/utils/text.py index 0ad1c8d..bb1f3c9 100644 --- a/IPython/utils/text.py +++ b/IPython/utils/text.py @@ -159,7 +159,7 @@ class SList(list): except IndexError: return "" - if isinstance(pattern, py3compat.string_types): + if isinstance(pattern, str): pred = lambda x : re.search(pattern, x, re.IGNORECASE) else: pred = pattern @@ -307,8 +307,10 @@ def list_strings(arg): Out[9]: ['A', 'list', 'of', 'strings'] """ - if isinstance(arg, py3compat.string_types): return [arg] - else: return arg + if isinstance(arg, str): + return [arg] + else: + return arg def marquee(txt='',width=78,mark='*'): @@ -619,10 +621,10 @@ def _col_chunks(l, max_rows, row_first=False): """Yield successive max_rows-sized column chunks from l.""" if row_first: ncols = (len(l) // max_rows) + (len(l) % max_rows > 0) - for i in py3compat.xrange(ncols): - yield [l[j] for j in py3compat.xrange(i, len(l), ncols)] + for i in range(ncols): + yield [l[j] for j in range(i, len(l), ncols)] else: - for i in py3compat.xrange(0, len(l), max_rows): + for i in range(0, len(l), max_rows): yield l[i:(i + max_rows)] diff --git a/IPython/utils/timing.py b/IPython/utils/timing.py index 99b7bbc..3d4d9f8 100644 --- a/IPython/utils/timing.py +++ b/IPython/utils/timing.py @@ -16,8 +16,6 @@ Utilities for timing code execution. import time -from .py3compat import xrange - #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- @@ -89,7 +87,7 @@ def timings_out(reps,func,*args,**kw): out = func(*args,**kw) tot_time = clock()-start else: - rng = xrange(reps-1) # the last time is executed separately to store output + rng = range(reps-1) # the last time is executed separately to store output start = clock() for dummy in rng: func(*args,**kw) out = func(*args,**kw) # one last time diff --git a/IPython/utils/ulinecache.py b/IPython/utils/ulinecache.py index f53b0dd..e12819d 100644 --- a/IPython/utils/ulinecache.py +++ b/IPython/utils/ulinecache.py @@ -25,8 +25,7 @@ else: filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding()) lines = linecache.getlines(filename, module_globals=module_globals) - # The bits we cache ourselves can be unicode. - if (not lines) or isinstance(lines[0], py3compat.unicode_type): + if (not lines) or isinstance(lines[0], str): return lines readline = openpy._list_readline(lines) diff --git a/IPython/utils/wildcard.py b/IPython/utils/wildcard.py index d22491b..cbef8c5 100644 --- a/IPython/utils/wildcard.py +++ b/IPython/utils/wildcard.py @@ -18,7 +18,6 @@ import re import types from IPython.utils.dir2 import dir2 -from .py3compat import iteritems def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]): """Return dictionaries mapping lower case typename (e.g. 'tuple') to type @@ -83,7 +82,7 @@ def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True, reg = re.compile(pattern+"$") # Check each one matches regex; shouldn't be hidden; of correct type. - return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \ + return dict((key,obj) for key, obj in ns.items() if reg.match(key) \ and show_hidden(key, show_all) \ and is_type(obj, type_pattern) ) @@ -103,10 +102,10 @@ def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all= type_pattern="all", ignore_case=ignore_case, show_all=show_all) results = {} - for name, obj in iteritems(filtered): + for name, obj in filtered.items(): ns = list_namespace(dict_dir(obj), type_pattern, ".".join(pattern_list[1:]), ignore_case=ignore_case, show_all=show_all) - for inner_name, inner_obj in iteritems(ns): + for inner_name, inner_obj in ns.items(): results["%s.%s"%(name,inner_name)] = inner_obj return results