diff options
author | Nikita Slyusarev <nslus@yandex-team.com> | 2022-02-10 16:46:52 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:46:52 +0300 |
commit | cd77cecfc03a3eaf87816af28a33067c4f0cdb59 (patch) | |
tree | 1308e0bae862d52e0020d881fe758080437fe389 /contrib/python/ipython/py2/IPython/core | |
parent | cdae02d225fb5b3afbb28990e79a7ac6c9125327 (diff) | |
download | ydb-cd77cecfc03a3eaf87816af28a33067c4f0cdb59.tar.gz |
Restoring authorship annotation for Nikita Slyusarev <nslus@yandex-team.com>. Commit 1 of 2.
Diffstat (limited to 'contrib/python/ipython/py2/IPython/core')
40 files changed, 1340 insertions, 1340 deletions
diff --git a/contrib/python/ipython/py2/IPython/core/alias.py b/contrib/python/ipython/py2/IPython/core/alias.py index 28a9ccb00d..be4e7eebed 100644 --- a/contrib/python/ipython/py2/IPython/core/alias.py +++ b/contrib/python/ipython/py2/IPython/core/alias.py @@ -29,7 +29,7 @@ from IPython.core.error import UsageError from IPython.utils.py3compat import string_types from traitlets import List, Instance -from logging import error +from logging import error #----------------------------------------------------------------------------- # Utilities @@ -192,8 +192,8 @@ class Alias(object): class AliasManager(Configurable): - default_aliases = List(default_aliases()).tag(config=True) - user_aliases = List(default_value=[]).tag(config=True) + default_aliases = List(default_aliases()).tag(config=True) + user_aliases = List(default_value=[]).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) def __init__(self, shell=None, **kwargs): diff --git a/contrib/python/ipython/py2/IPython/core/application.py b/contrib/python/ipython/py2/IPython/core/application.py index af28133945..32983540e7 100644 --- a/contrib/python/ipython/py2/IPython/core/application.py +++ b/contrib/python/ipython/py2/IPython/core/application.py @@ -13,7 +13,7 @@ object and then create the configurable objects, passing the config to them. # Distributed under the terms of the Modified BSD License. import atexit -from copy import deepcopy +from copy import deepcopy import glob import logging import os @@ -27,10 +27,10 @@ from IPython.core.profiledir import ProfileDir, ProfileDirError from IPython.paths import get_ipython_dir, get_ipython_package_dir from IPython.utils.path import ensure_dir_exists from IPython.utils import py3compat -from traitlets import ( - List, Unicode, Type, Bool, Dict, Set, Instance, Undefined, - default, observe, -) +from traitlets import ( + List, Unicode, Type, Bool, Dict, Set, Instance, Undefined, + default, observe, +) if os.name == 'nt': programdata = os.environ.get('PROGRAMDATA', None) @@ -52,16 +52,16 @@ if _env_config_dir not in SYSTEM_CONFIG_DIRS: ENV_CONFIG_DIRS.append(_env_config_dir) -_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS') -if _envvar in {None, ''}: - IPYTHON_SUPPRESS_CONFIG_ERRORS = None -else: - if _envvar.lower() in {'1','true'}: - IPYTHON_SUPPRESS_CONFIG_ERRORS = True - elif _envvar.lower() in {'0','false'} : - IPYTHON_SUPPRESS_CONFIG_ERRORS = False - else: - sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar ) +_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS') +if _envvar in {None, ''}: + IPYTHON_SUPPRESS_CONFIG_ERRORS = None +else: + if _envvar.lower() in {'1','true'}: + IPYTHON_SUPPRESS_CONFIG_ERRORS = True + elif _envvar.lower() in {'0','false'} : + IPYTHON_SUPPRESS_CONFIG_ERRORS = False + else: + sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar ) # aliases and flags @@ -118,13 +118,13 @@ class BaseIPythonApplication(Application): config_file_specified = Set() config_file_name = Unicode() - @default('config_file_name') + @default('config_file_name') def _config_file_name_default(self): return self.name.replace('-','_') + u'_config.py' - @observe('config_file_name') - def _config_file_name_changed(self, change): - if change['new'] != change['old']: - self.config_file_specified.add(change['new']) + @observe('config_file_name') + def _config_file_name_changed(self, change): + if change['new'] != change['old']: + self.config_file_specified.add(change['new']) # The directory that contains IPython's builtin profiles. builtin_profile_dir = Unicode( @@ -132,19 +132,19 @@ class BaseIPythonApplication(Application): ) config_file_paths = List(Unicode()) - @default('config_file_paths') + @default('config_file_paths') def _config_file_paths_default(self): return [py3compat.getcwd()] - extra_config_file = Unicode( + extra_config_file = Unicode( help="""Path to an extra config file to load. If specified, load this config file in addition to any other IPython config. - """).tag(config=True) - @observe('extra_config_file') - def _extra_config_file_changed(self, change): - old = change['old'] - new = change['new'] + """).tag(config=True) + @observe('extra_config_file') + def _extra_config_file_changed(self, change): + old = change['old'] + new = change['new'] try: self.config_files.remove(old) except ValueError: @@ -152,37 +152,37 @@ class BaseIPythonApplication(Application): self.config_file_specified.add(new) self.config_files.append(new) - profile = Unicode(u'default', + profile = Unicode(u'default', help="""The IPython profile to use.""" - ).tag(config=True) - - @observe('profile') - def _profile_changed(self, change): + ).tag(config=True) + + @observe('profile') + def _profile_changed(self, change): self.builtin_profile_dir = os.path.join( - get_ipython_package_dir(), u'config', u'profile', change['new'] + get_ipython_package_dir(), u'config', u'profile', change['new'] ) - ipython_dir = Unicode( + ipython_dir = Unicode( help=""" The name of the IPython directory. This directory is used for logging configuration (through profiles), history storage, etc. The default is usually $HOME/.ipython. This option can also be specified through the environment variable IPYTHONDIR. """ - ).tag(config=True) - @default('ipython_dir') + ).tag(config=True) + @default('ipython_dir') def _ipython_dir_default(self): d = get_ipython_dir() - self._ipython_dir_changed({ - 'name': 'ipython_dir', - 'old': d, - 'new': d, - }) + self._ipython_dir_changed({ + 'name': 'ipython_dir', + 'old': d, + 'new': d, + }) return d _in_init_profile_dir = False profile_dir = Instance(ProfileDir, allow_none=True) - @default('profile_dir') + @default('profile_dir') def _profile_dir_default(self): # avoid recursion if self._in_init_profile_dir: @@ -191,29 +191,29 @@ class BaseIPythonApplication(Application): self.init_profile_dir() return self.profile_dir - overwrite = Bool(False, - help="""Whether to overwrite existing config files when copying""" - ).tag(config=True) - auto_create = Bool(False, - help="""Whether to create profile dir if it doesn't exist""" - ).tag(config=True) + overwrite = Bool(False, + help="""Whether to overwrite existing config files when copying""" + ).tag(config=True) + auto_create = Bool(False, + help="""Whether to create profile dir if it doesn't exist""" + ).tag(config=True) config_files = List(Unicode()) - @default('config_files') + @default('config_files') def _config_files_default(self): return [self.config_file_name] - copy_config_files = Bool(False, + copy_config_files = Bool(False, help="""Whether to install the default config files into the profile dir. If a new profile is being created, and IPython contains config files for that profile, then they will be staged into the new directory. Otherwise, default config files will be automatically generated. - """).tag(config=True) + """).tag(config=True) - verbose_crash = Bool(False, + verbose_crash = Bool(False, help="""Create a massive crash report when IPython encounters what may be an internal error. The default is to append a short message to the - usual traceback""").tag(config=True) + usual traceback""").tag(config=True) # The class to use as the crash handler. crash_handler_class = Type(crashhandler.CrashHandler) @@ -239,8 +239,8 @@ class BaseIPythonApplication(Application): if subc in self.deprecated_subcommands: self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed " "in future versions.".format(sub=subc)) - self.log.warning("You likely want to use `jupyter {sub}` in the " - "future".format(sub=subc)) + self.log.warning("You likely want to use `jupyter {sub}` in the " + "future".format(sub=subc)) return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv) def init_crash_handler(self): @@ -262,11 +262,11 @@ class BaseIPythonApplication(Application): return self.crash_handler(etype, evalue, tb) else: return crashhandler.crash_handler_lite(etype, evalue, tb) - - @observe('ipython_dir') - def _ipython_dir_changed(self, change): - old = change['old'] - new = change['new'] + + @observe('ipython_dir') + def _ipython_dir_changed(self, change): + old = change['old'] + new = change['new'] if old is not Undefined: str_old = py3compat.cast_bytes_py2(os.path.abspath(old), sys.getfilesystemencoding() @@ -291,33 +291,33 @@ class BaseIPythonApplication(Application): self.log.error("couldn't create path %s: %s", path, e) self.log.debug("IPYTHONDIR set to: %s" % new) - def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS): + def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS): """Load the config file. By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail. - - `supress_errors` default value is to be `None` in which case the - behavior default to the one of `traitlets.Application`. - - The default value can be set : - - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive). - - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive). - - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset. - - Any other value are invalid, and will make IPython exit with a non-zero return code. + + `supress_errors` default value is to be `None` in which case the + behavior default to the one of `traitlets.Application`. + + The default value can be set : + - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive). + - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive). + - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset. + + Any other value are invalid, and will make IPython exit with a non-zero return code. """ - - + + self.log.debug("Searching path %s for config files", self.config_file_paths) base_config = 'ipython_config.py' self.log.debug("Attempting to load config file: %s" % base_config) try: - if suppress_errors is not None: - old_value = Application.raise_config_file_errors - Application.raise_config_file_errors = not suppress_errors; + if suppress_errors is not None: + old_value = Application.raise_config_file_errors + Application.raise_config_file_errors = not suppress_errors; Application.load_config_file( self, base_config, @@ -327,8 +327,8 @@ class BaseIPythonApplication(Application): # ignore errors loading parent self.log.debug("Config file %s not found", base_config) pass - if suppress_errors is not None: - Application.raise_config_file_errors = old_value + if suppress_errors is not None: + Application.raise_config_file_errors = old_value for config_file_name in self.config_files: if not config_file_name or config_file_name == base_config: @@ -457,9 +457,9 @@ class BaseIPythonApplication(Application): if self.subapp is not None: # stop here if subapp is taking over return - # save a copy of CLI config to re-load after config files - # so that it has highest priority - cl_config = deepcopy(self.config) + # save a copy of CLI config to re-load after config files + # so that it has highest priority + cl_config = deepcopy(self.config) self.init_profile_dir() self.init_config_files() self.load_config_file() diff --git a/contrib/python/ipython/py2/IPython/core/builtin_trap.py b/contrib/python/ipython/py2/IPython/core/builtin_trap.py index 909a555c73..ff857be949 100644 --- a/contrib/python/ipython/py2/IPython/core/builtin_trap.py +++ b/contrib/python/ipython/py2/IPython/core/builtin_trap.py @@ -57,7 +57,7 @@ class BuiltinTrap(Configurable): from IPython.lib import deepreload if self.shell.deep_reload: from warnings import warn - warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning) + warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning) self.auto_builtins['reload'] = deepreload._dreload else: self.auto_builtins['dreload']= deepreload._dreload diff --git a/contrib/python/ipython/py2/IPython/core/completer.py b/contrib/python/ipython/py2/IPython/core/completer.py index b386945e54..70bdee80ed 100644 --- a/contrib/python/ipython/py2/IPython/core/completer.py +++ b/contrib/python/ipython/py2/IPython/core/completer.py @@ -1,9 +1,9 @@ # encoding: utf-8 """Word completion for IPython. -This module started as fork of the rlcompleter module in the Python standard +This module started as fork of the rlcompleter module in the Python standard library. The original enhancements made to rlcompleter have been sent -upstream and were accepted as of Python 2.3, +upstream and were accepted as of Python 2.3, """ @@ -13,8 +13,8 @@ upstream and were accepted as of Python 2.3, # Some of this code originated from rlcompleter in the Python standard library # Copyright (C) 2001 Python Software Foundation, www.python.org -from __future__ import print_function - +from __future__ import print_function + import __main__ import glob import inspect @@ -27,18 +27,18 @@ import unicodedata import string import warnings -from traitlets.config.configurable import Configurable +from traitlets.config.configurable import Configurable from IPython.core.error import TryNext from IPython.core.inputsplitter import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.utils import generics from IPython.utils.decorators import undoc -from IPython.utils.dir2 import dir2, get_real_method +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 traitlets import Bool, Enum, observe - +from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2 +from traitlets import Bool, Enum, observe + # Public API __all__ = ['Completer','IPCompleter'] @@ -74,13 +74,13 @@ def has_open_quotes(s): def protect_filename(s): """Escape a string to protect certain characters.""" - if set(s) & set(PROTECTABLES): - if sys.platform == "win32": - return '"' + s + '"' - else: - return "".join(("\\" + c if c in PROTECTABLES else c) for c in s) - else: - return s + if set(s) & set(PROTECTABLES): + if sys.platform == "win32": + return '"' + s + '"' + else: + return "".join(("\\" + c if c in PROTECTABLES else c) for c in s) + else: + return s def expand_user(path): @@ -132,52 +132,52 @@ def compress_user(path, tilde_expand, tilde_val): return path -def completions_sorting_key(word): - """key for sorting completions +def completions_sorting_key(word): + """key for sorting completions - This does several things: + This does several things: - - Lowercase all completions, so they are sorted alphabetically with - upper and lower case words mingled - - Demote any completions starting with underscores to the end - - Insert any %magic and %%cellmagic completions in the alphabetical order - by their name - """ - # Case insensitive sort - word = word.lower() + - Lowercase all completions, so they are sorted alphabetically with + upper and lower case words mingled + - Demote any completions starting with underscores to the end + - Insert any %magic and %%cellmagic completions in the alphabetical order + by their name + """ + # Case insensitive sort + word = word.lower() - prio1, prio2 = 0, 0 + prio1, prio2 = 0, 0 - if word.startswith('__'): - prio1 = 2 - elif word.startswith('_'): - prio1 = 1 + if word.startswith('__'): + prio1 = 2 + elif word.startswith('_'): + prio1 = 1 - if word.endswith('='): - prio1 = -1 + if word.endswith('='): + prio1 = -1 - if word.startswith('%%'): - # If there's another % in there, this is something else, so leave it alone + if word.startswith('%%'): + # If there's another % in there, this is something else, so leave it alone if not "%" in word[2:]: - word = word[2:] - prio2 = 2 - elif word.startswith('%'): + word = word[2:] + prio2 = 2 + elif word.startswith('%'): if not "%" in word[1:]: - word = word[1:] - prio2 = 1 - - return prio1, word, prio2 + word = word[1:] + prio2 = 1 + return prio1, word, prio2 + @undoc class Bunch(object): pass -if sys.platform == 'win32': - DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' -else: - DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' - +if sys.platform == 'win32': + DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' +else: + DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' + GREEDY_DELIMS = ' =\r\n' @@ -234,14 +234,14 @@ class CompletionSplitter(object): class Completer(Configurable): - greedy = Bool(False, + greedy = Bool(False, help="""Activate greedy completion - PENDING DEPRECTION. this is now mostly taken care of with Jedi. + PENDING DEPRECTION. this is now mostly taken care of with Jedi. This will enable completion on elements of lists, results of function calls, etc., but can be unsafe because the code is actually evaluated on TAB. """ - ).tag(config=True) + ).tag(config=True) backslash_combining_completions = Bool(True, help="Enable unicode completions, e.g. \\alpha<tab> . " @@ -251,7 +251,7 @@ class Completer(Configurable): def __init__(self, namespace=None, global_namespace=None, **kwargs): """Create a new completer for the command line. - Completer(namespace=ns, global_namespace=ns2) -> completer instance. + Completer(namespace=ns, global_namespace=ns2) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be @@ -321,7 +321,7 @@ class Completer(Configurable): for word in lst: if word[:n] == text and word != "__builtins__": match_append(word) - return [cast_unicode_py2(m) for m in matches] + return [cast_unicode_py2(m) for m in matches] def attr_matches(self, text): """Compute matches when text contains a dot. @@ -373,7 +373,7 @@ class Completer(Configurable): pass # Build match list to return n = len(attr) - return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] + return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] def get__all__entries(obj): @@ -383,7 +383,7 @@ 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, string_types)] def match_dict_keys(keys, prefix, delims): @@ -470,7 +470,7 @@ def back_unicode_name_matches(text): try : unic = unicodedata.name(char) return '\\'+char,['\\'+unic] - except KeyError: + except KeyError: pass return u'', () @@ -497,18 +497,18 @@ def back_latex_name_matches(text): latex = reverse_latex_symbol[char] # '\\' replace the \ as well return '\\'+char,[latex] - except KeyError: + except KeyError: pass return u'', () class IPCompleter(Completer): """Extension of the completer class with IPython-specific features""" - - @observe('greedy') - def _greedy_changed(self, change): + + @observe('greedy') + def _greedy_changed(self, change): """update the splitter and readline delims when greedy is changed""" - if change['new']: + if change['new']: self.splitter.delims = GREEDY_DELIMS else: self.splitter.delims = DELIMS @@ -516,14 +516,14 @@ class IPCompleter(Completer): if self.readline: self.readline.set_completer_delims(self.splitter.delims) - merge_completions = Bool(True, + merge_completions = Bool(True, help="""Whether to merge completion results into a single list If False, only the completion results from the first non-empty completer will be returned. """ - ).tag(config=True) - omit__names = Enum((0,1,2), default_value=2, + ).tag(config=True) + omit__names = Enum((0,1,2), default_value=2, help="""Instruct the completer to omit private method names Specifically, when completing on ``object.<tab>``. @@ -534,20 +534,20 @@ class IPCompleter(Completer): When 0: nothing will be excluded. """ - ).tag(config=True) - limit_to__all__ = Bool(False, - help=""" - DEPRECATED as of version 5.0. - - Instruct the completer to use __all__ for the completion + ).tag(config=True) + limit_to__all__ = Bool(False, + help=""" + DEPRECATED as of version 5.0. + Instruct the completer to use __all__ for the completion + Specifically, when completing on ``object.<tab>``. When True: only those names in obj.__all__ will be included. When False [default]: the __all__ attribute is ignored - """, - ).tag(config=True) + """, + ).tag(config=True) @observe('limit_to__all__') def _limit_to_all_changed(self, change): @@ -621,24 +621,24 @@ class IPCompleter(Completer): #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') # All active matcher routines for completion - self.matchers = [ - self.python_matches, + self.matchers = [ + self.python_matches, self.file_matches, self.magic_matches, self.python_func_kw_matches, self.dict_key_matches, ] - # This is set externally by InteractiveShell - self.custom_completers = None - + # This is set externally by InteractiveShell + self.custom_completers = None + def all_completions(self, text): """ - Wrapper around the complete method for the benefit of emacs. + Wrapper around the complete method for the benefit of emacs. """ return self.complete(text)[1] - def _clean_glob(self, text): + def _clean_glob(self, text): return self.glob("%s*" % text) def _clean_glob_win32(self,text): @@ -665,9 +665,9 @@ class IPCompleter(Completer): # when escaped with backslash if text.startswith('!'): text = text[1:] - text_prefix = u'!' + text_prefix = u'!' else: - text_prefix = u'' + text_prefix = u'' text_until_cursor = self.text_until_cursor # track strings with open quotes @@ -698,13 +698,13 @@ class IPCompleter(Completer): text = os.path.expanduser(text) if text == "": - return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")] + return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")] # Compute the matches from the filesystem - if sys.platform == 'win32': - m0 = self.clean_glob(text) - else: - m0 = self.clean_glob(text.replace('\\', '')) + if sys.platform == 'win32': + m0 = self.clean_glob(text) + else: + m0 = self.clean_glob(text.replace('\\', '')) if has_protectables: # If we had protectables, we need to revert our changes to the @@ -724,7 +724,7 @@ class IPCompleter(Completer): protect_filename(f) for f in m0] # Mark directories in input list by appending '/' to their names. - return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches] + return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches] def magic_matches(self, text): """Match magics""" @@ -745,10 +745,10 @@ class IPCompleter(Completer): comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] if not text.startswith(pre2): comp += [ pre+m for m in line_magics if m.startswith(bare_text)] - return [cast_unicode_py2(c) for c in comp] - + return [cast_unicode_py2(c) for c in comp] - def python_matches(self, text): + + def python_matches(self, text): """Match attributes or global python names""" if "." in text: try: @@ -896,19 +896,19 @@ class IPCompleter(Completer): for namedArg in namedArgs: if namedArg.startswith(text): - argMatches.append(u"%s=" %namedArg) + argMatches.append(u"%s=" %namedArg) return argMatches def dict_key_matches(self, text): "Match string keys in a dictionary, after e.g. 'foo[' " def get_keys(obj): - # Objects can define their own completions by defining an - # _ipy_key_completions_() method. - method = get_real_method(obj, '_ipython_key_completions_') - if method is not None: - return method() - - # Special case some common in-memory dict-like types + # Objects can define their own completions by defining an + # _ipy_key_completions_() method. + method = get_real_method(obj, '_ipython_key_completions_') + if method is not None: + return method() + + # Special case some common in-memory dict-like types if isinstance(obj, dict) or\ _safe_isinstance(obj, 'pandas', 'DataFrame'): try: @@ -1026,7 +1026,7 @@ class IPCompleter(Completer): # allow combining chars if ('a'+unic).isidentifier(): return '\\'+s,[unic] - except KeyError: + except KeyError: pass return u'', [] @@ -1055,9 +1055,9 @@ class IPCompleter(Completer): return u'', [] def dispatch_custom_completer(self, text): - if not self.custom_completers: - return - + if not self.custom_completers: + return + line = self.line_buffer if not line.strip(): return None @@ -1085,12 +1085,12 @@ class IPCompleter(Completer): res = c(event) if res: # first, try case sensitive match - withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)] + withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)] if withcase: return withcase # if none, then case insensitive ones are ok too text_low = text.lower() - return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] + return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] except TryNext: pass except KeyboardInterrupt: diff --git a/contrib/python/ipython/py2/IPython/core/completerlib.py b/contrib/python/ipython/py2/IPython/core/completerlib.py index e736ca73d1..5d51991725 100644 --- a/contrib/python/ipython/py2/IPython/core/completerlib.py +++ b/contrib/python/ipython/py2/IPython/core/completerlib.py @@ -227,8 +227,8 @@ def try_import(mod, only_modules=False): completions.extend(getattr(m, '__all__', [])) if m_is_init: completions.extend(arcadia_module_list(mod)) - completions = {c for c in completions if isinstance(c, string_types)} - completions.discard('__init__') + completions = {c for c in completions if isinstance(c, string_types)} + completions.discard('__init__') return sorted(completions) diff --git a/contrib/python/ipython/py2/IPython/core/debugger.py b/contrib/python/ipython/py2/IPython/core/debugger.py index f08cfb1a78..4980c3551b 100644 --- a/contrib/python/ipython/py2/IPython/core/debugger.py +++ b/contrib/python/ipython/py2/IPython/core/debugger.py @@ -31,40 +31,40 @@ import bdb import functools import inspect import sys -import warnings +import warnings from IPython import get_ipython from IPython.utils import PyColorize, ulinecache -from IPython.utils import coloransi, py3compat +from IPython.utils import coloransi, py3compat from IPython.core.excolors import exception_colors from IPython.testing.skipdoctest import skip_doctest - + prompt = 'ipdb> ' - + #We have to check this directly from sys.argv, config struct not yet available -from pdb import Pdb as OldPdb +from pdb import Pdb as OldPdb # Allow the set_trace code to operate outside of an ipython instance, even if # it does so with some limitations. The rest of this support is implemented in # the Tracer constructor. - -def make_arrow(pad): - """generate the leading arrow in front of traceback or debugger""" - if pad >= 2: - return '-'*(pad-2) + '> ' - elif pad == 1: - return '>' - return '' - - + +def make_arrow(pad): + """generate the leading arrow in front of traceback or debugger""" + if pad >= 2: + return '-'*(pad-2) + '> ' + elif pad == 1: + return '>' + return '' + + def BdbQuit_excepthook(et, ev, tb, excepthook=None): """Exception hook which handles `BdbQuit` exceptions. All other exceptions are processed using the `excepthook` parameter. """ - warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1", + warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1", DeprecationWarning, stacklevel=2) if et==bdb.BdbQuit: print('Exiting Debugger.') @@ -74,20 +74,20 @@ def BdbQuit_excepthook(et, ev, tb, excepthook=None): # Backwards compatibility. Raise deprecation warning? BdbQuit_excepthook.excepthook_ori(et,ev,tb) - + def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): - warnings.warn( - "`BdbQuit_IPython_excepthook` is deprecated since version 5.1", + warnings.warn( + "`BdbQuit_IPython_excepthook` is deprecated since version 5.1", DeprecationWarning, stacklevel=2) print('Exiting Debugger.') class Tracer(object): - """ - DEPRECATED - - Class for local debugging, similar to pdb.set_trace. + """ + DEPRECATED + Class for local debugging, similar to pdb.set_trace. + Instances of this class, when called, behave like pdb.set_trace, but providing IPython's enhanced capabilities. @@ -100,11 +100,11 @@ class Tracer(object): @skip_doctest def __init__(self, colors=None): - """ - DEPRECATED - - Create a local debugger instance. + """ + DEPRECATED + Create a local debugger instance. + Parameters ---------- @@ -128,8 +128,8 @@ class Tracer(object): step through code, set breakpoints, etc. See the pdb documentation from the Python standard library for usage details. """ - warnings.warn("`Tracer` is deprecated since version 5.1, directly use " - "`IPython.core.debugger.Pdb.set_trace()`", + warnings.warn("`Tracer` is deprecated since version 5.1, directly use " + "`IPython.core.debugger.Pdb.set_trace()`", DeprecationWarning, stacklevel=2) ip = get_ipython() @@ -204,25 +204,25 @@ def _file_lines(fname): class Pdb(OldPdb): - """Modified Pdb class, does not load readline. - - for a standalone version that uses prompt_toolkit, see - `IPython.terminal.debugger.TerminalPdb` and - `IPython.terminal.debugger.set_trace()` - """ - - def __init__(self, color_scheme=None, completekey=None, + """Modified Pdb class, does not load readline. + + for a standalone version that uses prompt_toolkit, see + `IPython.terminal.debugger.TerminalPdb` and + `IPython.terminal.debugger.set_trace()` + """ + + def __init__(self, color_scheme=None, completekey=None, stdin=None, stdout=None, context=5): # Parent constructor: try: - self.context = int(context) + self.context = int(context) if self.context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError): raise ValueError("Context must be a positive integer") - OldPdb.__init__(self, completekey, stdin, stdout) + OldPdb.__init__(self, completekey, stdin, stdout) # IPython changes... self.shell = get_ipython() @@ -237,12 +237,12 @@ class Pdb(OldPdb): # the debugger was entered. See also #9941. sys.modules['__main__'] = save_main - if color_scheme is not None: - warnings.warn( - "The `color_scheme` argument is deprecated since version 5.1", - DeprecationWarning) - else: - color_scheme = self.shell.colors + if color_scheme is not None: + warnings.warn( + "The `color_scheme` argument is deprecated since version 5.1", + DeprecationWarning) + else: + color_scheme = self.shell.colors self.aliases = {} @@ -266,28 +266,28 @@ class Pdb(OldPdb): cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red - cst['Neutral'].colors.prompt = C.Blue - cst['Neutral'].colors.breakpoint_enabled = C.LightRed - cst['Neutral'].colors.breakpoint_disabled = C.Red - + cst['Neutral'].colors.prompt = C.Blue + cst['Neutral'].colors.breakpoint_enabled = C.LightRed + cst['Neutral'].colors.breakpoint_disabled = C.Red + self.set_colors(color_scheme) # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser() - # Set the prompt - the default prompt is '(Pdb)' - self.prompt = prompt + # Set the prompt - the default prompt is '(Pdb)' + self.prompt = prompt def set_colors(self, scheme): """Shorthand access to the color table scheme selector method.""" self.color_scheme_table.set_active_scheme(scheme) def interaction(self, frame, traceback): - try: - OldPdb.interaction(self, frame, traceback) - except KeyboardInterrupt: - sys.stdout.write('\n' + self.shell.get_exception_only()) + try: + OldPdb.interaction(self, frame, traceback) + except KeyboardInterrupt: + sys.stdout.write('\n' + self.shell.get_exception_only()) def new_do_up(self, arg): OldPdb.do_up(self, arg) @@ -331,7 +331,7 @@ class Pdb(OldPdb): except KeyboardInterrupt: pass - def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ', + def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ', context=None): if context is None: context = self.context @@ -341,7 +341,7 @@ class Pdb(OldPdb): raise ValueError("Context must be a positive integer") except (TypeError, ValueError): raise ValueError("Context must be a positive integer") - print(self.format_stack_entry(frame_lineno, '', context)) + print(self.format_stack_entry(frame_lineno, '', context)) # vds: >> frame, lineno = frame_lineno @@ -447,11 +447,11 @@ class Pdb(OldPdb): if arrow: # This is the line with the error pad = numbers_width - len(str(lineno)) - len(bp_mark) - num = '%s%s' % (make_arrow(pad), str(lineno)) + num = '%s%s' % (make_arrow(pad), str(lineno)) else: num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) - return tpl_line % (bp_mark_color + bp_mark, num, line) + return tpl_line % (bp_mark_color + bp_mark, num, line) def print_list_lines(self, filename, first, last): @@ -479,7 +479,7 @@ class Pdb(OldPdb): src.append(line) self.lineno = lineno - print(''.join(src)) + print(''.join(src)) except KeyboardInterrupt: pass diff --git a/contrib/python/ipython/py2/IPython/core/display.py b/contrib/python/ipython/py2/IPython/core/display.py index 5c82a57b31..a099031953 100644 --- a/contrib/python/ipython/py2/IPython/core/display.py +++ b/contrib/python/ipython/py2/IPython/core/display.py @@ -6,17 +6,17 @@ from __future__ import print_function -try: - from base64 import encodebytes as base64_encode -except ImportError: - from base64 import encodestring as base64_encode - +try: + from base64 import encodebytes as base64_encode +except ImportError: + from base64 import encodestring as base64_encode + from binascii import b2a_hex, hexlify import json import mimetypes import os import struct -import sys +import sys import warnings from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, @@ -964,9 +964,9 @@ class Image(DisplayObject): Note that QtConsole is not able to display images if `embed` is set to `False` width : int - Width in pixels to which to constrain the image in html + Width in pixels to which to constrain the image in html height : int - Height in pixels to which to constrain the image in html + Height in pixels to which to constrain the image in html retina : bool Automatically set the width and height to half of the measured width and height. @@ -1111,7 +1111,7 @@ class Image(DisplayObject): class Video(DisplayObject): - def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None): + def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None): """Create a video object given raw data or an URL. When this object is returned by an input cell or passed to the @@ -1121,54 +1121,54 @@ class Video(DisplayObject): Parameters ---------- data : unicode, str or bytes - The raw video data or a URL or filename to load the data from. - Raw data will require passing `embed=True`. + The raw video data or a URL or filename to load the data from. + Raw data will require passing `embed=True`. url : unicode - A URL for the video. If you specify `url=`, - the image data will not be embedded. + A URL for the video. If you specify `url=`, + the image data will not be embedded. filename : unicode - Path to a local file containing the video. - Will be interpreted as a local URL unless `embed=True`. + Path to a local file containing the video. + Will be interpreted as a local URL unless `embed=True`. embed : bool - Should the video be embedded using a data URI (True) or be - loaded using a <video> tag (False). - - Since videos are large, embedding them should be avoided, if possible. - You must confirm embedding as your intention by passing `embed=True`. - - Local files can be displayed with URLs without embedding the content, via:: + Should the video be embedded using a data URI (True) or be + loaded using a <video> tag (False). - Video('./video.mp4') + Since videos are large, embedding them should be avoided, if possible. + You must confirm embedding as your intention by passing `embed=True`. + Local files can be displayed with URLs without embedding the content, via:: + + Video('./video.mp4') + mimetype: unicode - Specify the mimetype for embedded videos. - Default will be guessed from file extension, if available. - + Specify the mimetype for embedded videos. + Default will be guessed from file extension, if available. + Examples -------- - + Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') Video('path/to/video.mp4') - Video('path/to/video.mp4', embed=True) - Video(b'raw-videodata', embed=True) + 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, string_types) and data.startswith(('http:', 'https:')): url = data data = None elif os.path.exists(data): filename = data data = None - - if data and not embed: - msg = ''.join([ - "To embed videos, you must pass embed=True ", - "(this may make your notebook files huge)\n", - "Consider passing Video(url='...')", - ]) - raise ValueError(msg) + + if data and not embed: + msg = ''.join([ + "To embed videos, you must pass embed=True ", + "(this may make your notebook files huge)\n", + "Consider passing Video(url='...')", + ]) + raise ValueError(msg) self.mimetype = mimetype - self.embed = embed + self.embed = embed super(Video, self).__init__(data=data, url=url, filename=filename) def _repr_html_(self): @@ -1180,27 +1180,27 @@ class Video(DisplayObject): Your browser does not support the <code>video</code> element. </video>""".format(url) return output - - # Embedded videos are base64-encoded. - mimetype = self.mimetype + + # Embedded videos are base64-encoded. + mimetype = self.mimetype if self.filename is not None: - if not mimetype: - mimetype, _ = mimetypes.guess_type(self.filename) - - with open(self.filename, 'rb') as f: - video = f.read() + if not mimetype: + mimetype, _ = mimetypes.guess_type(self.filename) + + with open(self.filename, 'rb') as f: + video = f.read() else: - video = self.data - if isinstance(video, unicode_type): - # unicode input is already b64-encoded - b64_video = video - else: - b64_video = base64_encode(video).decode('ascii').rstrip() - + video = self.data + if isinstance(video, unicode_type): + # unicode input is already b64-encoded + b64_video = video + else: + b64_video = base64_encode(video).decode('ascii').rstrip() + output = """<video controls> <source src="data:{0};base64,{1}" type="{0}"> Your browser does not support the video tag. - </video>""".format(mimetype, b64_video) + </video>""".format(mimetype, b64_video) return output def reload(self): @@ -1225,10 +1225,10 @@ def clear_output(wait=False): if InteractiveShell.initialized(): InteractiveShell.instance().display_pub.clear_output(wait) else: - print('\033[2K\r', end='') - sys.stdout.flush() - print('\033[2K\r', end='') - sys.stderr.flush() + print('\033[2K\r', end='') + sys.stdout.flush() + print('\033[2K\r', end='') + sys.stderr.flush() @skip_doctest diff --git a/contrib/python/ipython/py2/IPython/core/displayhook.py b/contrib/python/ipython/py2/IPython/core/displayhook.py index cce7c83d16..e07b577680 100644 --- a/contrib/python/ipython/py2/IPython/core/displayhook.py +++ b/contrib/python/ipython/py2/IPython/core/displayhook.py @@ -16,7 +16,7 @@ import tokenize from traitlets.config.configurable import Configurable from IPython.utils.py3compat import builtin_mod, cast_unicode_py2 from traitlets import Instance, Float -from warnings import warn +from warnings import warn # TODO: Move the various attributes (cache_size, [others now moved]). Some # of these are also attributes of InteractiveShell. They should be on ONE object @@ -94,7 +94,7 @@ class DisplayHook(Configurable): tokens = list(tokenize.generate_tokens(sio.readline)) for token in reversed(tokens): - if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): + if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): continue if (token[0] == tokenize.OP) and (token[1] == ';'): return True @@ -109,13 +109,13 @@ class DisplayHook(Configurable): """Write the output prompt. The default implementation simply writes the prompt to - ``sys.stdout``. + ``sys.stdout``. """ # Use write, not print which adds an extra space. - sys.stdout.write(self.shell.separate_out) - outprompt = 'Out[{}]: '.format(self.shell.execution_count) + sys.stdout.write(self.shell.separate_out) + outprompt = 'Out[{}]: '.format(self.shell.execution_count) if self.do_full_cache: - sys.stdout.write(outprompt) + sys.stdout.write(outprompt) def compute_format_data(self, result): """Compute format data of the object to be displayed. @@ -149,14 +149,14 @@ class DisplayHook(Configurable): """ return self.shell.display_formatter.format(result) - # This can be set to True by the write_output_prompt method in a subclass - prompt_end_newline = False - + # This can be set to True by the write_output_prompt method in a subclass + prompt_end_newline = False + def write_format_data(self, format_dict, md_dict=None): """Write the format data dict to the frontend. This default version of this method simply writes the plain text - representation of the object to ``sys.stdout``. Subclasses should + representation of the object to ``sys.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends. @@ -182,11 +182,11 @@ class DisplayHook(Configurable): # because the expansion may add ANSI escapes that will interfere # with our ability to determine whether or not we should add # a newline. - if not self.prompt_end_newline: + if not self.prompt_end_newline: # But avoid extraneous empty lines. result_repr = '\n' + result_repr - print(result_repr) + print(result_repr) def update_user_ns(self, result): """Update user_ns with various things like _, __, _1, etc.""" @@ -230,8 +230,8 @@ class DisplayHook(Configurable): def finish_displayhook(self): """Finish up all displayhook activities.""" - sys.stdout.write(self.shell.separate_out2) - sys.stdout.flush() + sys.stdout.write(self.shell.separate_out2) + sys.stdout.flush() def __call__(self, result=None): """Printing with history cache management. diff --git a/contrib/python/ipython/py2/IPython/core/displaypub.py b/contrib/python/ipython/py2/IPython/core/displaypub.py index 82a859ae15..cd7be5797e 100644 --- a/contrib/python/ipython/py2/IPython/core/displaypub.py +++ b/contrib/python/ipython/py2/IPython/core/displaypub.py @@ -17,8 +17,8 @@ spec. from __future__ import print_function -import sys - +import sys + from traitlets.config.configurable import Configurable from traitlets import List @@ -105,16 +105,16 @@ class DisplayPublisher(Configurable): transient = kwargs.pop('transient', None) update = kwargs.pop('update', False) - # The default is to simply write the plain text data using sys.stdout. + # The default is to simply write the plain text data using sys.stdout. if 'text/plain' in data: - print(data['text/plain']) + print(data['text/plain']) def clear_output(self, wait=False): """Clear the output of the cell receiving output.""" - print('\033[2K\r', end='') - sys.stdout.flush() - print('\033[2K\r', end='') - sys.stderr.flush() + print('\033[2K\r', end='') + sys.stdout.flush() + print('\033[2K\r', end='') + sys.stderr.flush() class CapturingDisplayPublisher(DisplayPublisher): diff --git a/contrib/python/ipython/py2/IPython/core/events.py b/contrib/python/ipython/py2/IPython/core/events.py index bfd09fec6a..776fa191da 100644 --- a/contrib/python/ipython/py2/IPython/core/events.py +++ b/contrib/python/ipython/py2/IPython/core/events.py @@ -69,7 +69,7 @@ class EventManager(object): Any additional arguments are passed to all callbacks registered for this event. Exceptions raised by callbacks are caught, and a message printed. """ - for func in self.callbacks[event][:]: + for func in self.callbacks[event][:]: try: func(*args, **kwargs) except Exception: diff --git a/contrib/python/ipython/py2/IPython/core/excolors.py b/contrib/python/ipython/py2/IPython/core/excolors.py index 487bde18c8..de46ac13a5 100644 --- a/contrib/python/ipython/py2/IPython/core/excolors.py +++ b/contrib/python/ipython/py2/IPython/core/excolors.py @@ -19,7 +19,7 @@ def exception_colors(): """Return a color table with fields for exception reporting. The table is an instance of ColorSchemeTable with schemes added for - 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled + 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled in. Examples: @@ -128,41 +128,41 @@ def exception_colors(): Normal = C.Normal, )) - ex_colors.add_scheme(ColorScheme( - 'Neutral', - # The color to be used for the top line - topline = C.Red, - - # The colors to be used in the traceback - filename = C.LightGreen, - lineno = C.LightGreen, - name = C.LightPurple, - vName = C.Cyan, - val = C.LightGreen, - em = C.Cyan, - - # Emphasized colors for the last frame of the traceback - normalEm = C.Cyan, - filenameEm = C.Green, - linenoEm = C.Green, - nameEm = C.Purple, - valEm = C.Blue, - - # Colors for printing the exception - excName = C.Red, - #line = C.Brown, # brown often is displayed as yellow - line = C.Red, - caret = C.Normal, - Normal = C.Normal, - )) - + ex_colors.add_scheme(ColorScheme( + 'Neutral', + # The color to be used for the top line + topline = C.Red, + + # The colors to be used in the traceback + filename = C.LightGreen, + lineno = C.LightGreen, + name = C.LightPurple, + vName = C.Cyan, + val = C.LightGreen, + em = C.Cyan, + + # Emphasized colors for the last frame of the traceback + normalEm = C.Cyan, + filenameEm = C.Green, + linenoEm = C.Green, + nameEm = C.Purple, + valEm = C.Blue, + + # Colors for printing the exception + excName = C.Red, + #line = C.Brown, # brown often is displayed as yellow + line = C.Red, + caret = C.Normal, + Normal = C.Normal, + )) + # Hack: the 'neutral' colours are not very visible on a dark background on # Windows. Since Windows command prompts have a dark background by default, and # relatively few users are likely to alter that, we will use the 'Linux' colours, # designed for a dark background, as the default on Windows. if os.name == "nt": ex_colors.add_scheme(ex_colors['Linux'].copy('Neutral')) - + return ex_colors class Deprec(object): diff --git a/contrib/python/ipython/py2/IPython/core/extensions.py b/contrib/python/ipython/py2/IPython/core/extensions.py index 58855466f1..81c5de462d 100644 --- a/contrib/python/ipython/py2/IPython/core/extensions.py +++ b/contrib/python/ipython/py2/IPython/core/extensions.py @@ -36,7 +36,7 @@ class ExtensionManager(Configurable): the only argument. You can do anything you want with IPython at that point, including defining new magic and aliases, adding new components, etc. - + You can also optionally define an :func:`unload_ipython_extension(ipython)` function, which will be called if the user unloads or reloads the extension. The extension manager will only call :func:`load_ipython_extension` again @@ -49,12 +49,12 @@ class ExtensionManager(Configurable): is added to ``sys.path`` automatically. """ - shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) def __init__(self, shell=None, **kwargs): super(ExtensionManager, self).__init__(shell=shell, **kwargs) - self.shell.observe( - self._on_ipython_dir_changed, names=('ipython_dir',) + self.shell.observe( + self._on_ipython_dir_changed, names=('ipython_dir',) ) self.loaded = set() @@ -62,7 +62,7 @@ class ExtensionManager(Configurable): def ipython_extension_dir(self): return os.path.join(self.shell.ipython_dir, u'extensions') - def _on_ipython_dir_changed(self, change): + def _on_ipython_dir_changed(self, change): ensure_dir_exists(self.ipython_extension_dir) def load_extension(self, module_str): @@ -74,7 +74,7 @@ class ExtensionManager(Configurable): """ if module_str in self.loaded: return "already loaded" - + with self.shell.builtin_trap: if module_str not in sys.modules: try: @@ -92,14 +92,14 @@ class ExtensionManager(Configurable): This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. - + Returns the string "no unload function" if the extension doesn't define a function to unload itself, "not loaded" if the extension isn't loaded, otherwise None. """ if module_str not in self.loaded: return "not loaded" - + if module_str in sys.modules: mod = sys.modules[module_str] if self._call_unload_ipython_extension(mod): @@ -138,7 +138,7 @@ class ExtensionManager(Configurable): return True def install_extension(self, url, filename=None): - """Download and install an IPython extension. + """Download and install an IPython extension. If filename is given, the file will be so named (inside the extension directory). Otherwise, the name from the URL will be used. The file must diff --git a/contrib/python/ipython/py2/IPython/core/formatters.py b/contrib/python/ipython/py2/IPython/core/formatters.py index d990619f27..06af83c1a9 100644 --- a/contrib/python/ipython/py2/IPython/core/formatters.py +++ b/contrib/python/ipython/py2/IPython/core/formatters.py @@ -21,12 +21,12 @@ from decorator import decorator from traitlets.config.configurable import Configurable from IPython.core.getipython import get_ipython from IPython.utils.sentinel import Sentinel -from IPython.utils.dir2 import get_real_method +from IPython.utils.dir2 import get_real_method from IPython.lib import pretty from traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, - default, observe, + default, observe, ) from IPython.utils.py3compat import ( with_metaclass, string_types, unicode_type, @@ -35,28 +35,28 @@ from IPython.utils.py3compat import ( class DisplayFormatter(Configurable): - active_types = List(Unicode(), + active_types = List(Unicode(), help="""List of currently active mime-types to display. You can use this to set a white-list for formats to display. Most users will not need to change this value. - """).tag(config=True) - - @default('active_types') + """).tag(config=True) + + @default('active_types') def _active_types_default(self): return self.format_types - - @observe('active_types') - def _active_types_changed(self, change): + + @observe('active_types') + def _active_types_changed(self, change): for key, formatter in self.formatters.items(): - if key in change['new']: + if key in change['new']: formatter.enabled = True else: formatter.enabled = False ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') - @default('ipython_display_formatter') - def _default_formatter(self): + @default('ipython_display_formatter') + def _default_formatter(self): return IPythonDisplayFormatter(parent=self) mimebundle_formatter = ForwardDeclaredInstance('FormatterABC') @@ -67,7 +67,7 @@ class DisplayFormatter(Configurable): # A dict of formatter whose keys are format types (MIME types) and whose # values are subclasses of BaseFormatter. formatters = Dict() - @default('formatters') + @default('formatters') def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ @@ -305,21 +305,21 @@ class BaseFormatter(Configurable): format_type = Unicode('text/plain') _return_type = string_types - enabled = Bool(True).tag(config=True) + enabled = Bool(True).tag(config=True) print_method = ObjectName('__repr__') # The singleton printers. # Maps the IDs of the builtin singleton objects to the format functions. - singleton_printers = Dict().tag(config=True) + singleton_printers = Dict().tag(config=True) # The type-specific printers. # Map type objects to the format functions. - type_printers = Dict().tag(config=True) + type_printers = Dict().tag(config=True) # The deferred-import type-specific printers. # Map (modulename, classname) pairs to the format functions. - deferred_printers = Dict().tag(config=True) + deferred_printers = Dict().tag(config=True) @catch_format_error def __call__(self, obj): @@ -333,7 +333,7 @@ class BaseFormatter(Configurable): else: return printer(obj) # Finally look for special method names - method = get_real_method(obj, self.print_method) + method = get_real_method(obj, self.print_method) if method is not None: return method() return None @@ -586,37 +586,37 @@ class PlainTextFormatter(BaseFormatter): # This subclass ignores this attribute as it always need to return # something. - enabled = Bool(True).tag(config=False) + enabled = Bool(True).tag(config=False) - max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, + max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, help="""Truncate large collections (lists, dicts, tuples, sets) to this size. Set to 0 to disable truncation. """ - ).tag(config=True) + ).tag(config=True) # Look for a _repr_pretty_ methods to use for pretty printing. print_method = ObjectName('_repr_pretty_') # Whether to pretty-print or not. - pprint = Bool(True).tag(config=True) + pprint = Bool(True).tag(config=True) # Whether to be verbose or not. - verbose = Bool(False).tag(config=True) + verbose = Bool(False).tag(config=True) # The maximum width. - max_width = Integer(79).tag(config=True) + max_width = Integer(79).tag(config=True) # The newline character. - newline = Unicode('\n').tag(config=True) + newline = Unicode('\n').tag(config=True) # format-string for pprinting floats float_format = Unicode('%r') # setter for float precision, either int or direct format-string - float_precision = CUnicode('').tag(config=True) + float_precision = CUnicode('').tag(config=True) - @observe('float_precision') - def _float_precision_changed(self, change): + @observe('float_precision') + def _float_precision_changed(self, change): """float_precision changed, set float_format accordingly. float_precision can be set by int or str. @@ -630,7 +630,7 @@ class PlainTextFormatter(BaseFormatter): This parameter can be set via the '%precision' magic. """ - new = change['new'] + new = change['new'] if '%' in new: # got explicit format string fmt = new @@ -663,17 +663,17 @@ class PlainTextFormatter(BaseFormatter): self.float_format = fmt # Use the default pretty printers from IPython.lib.pretty. - @default('singleton_printers') + @default('singleton_printers') def _singleton_printers_default(self): return pretty._singleton_pprinters.copy() - @default('type_printers') + @default('type_printers') def _type_printers_default(self): d = pretty._type_pprinters.copy() d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) return d - @default('deferred_printers') + @default('deferred_printers') def _deferred_printers_default(self): return pretty._deferred_type_pprinters.copy() @@ -910,7 +910,7 @@ class IPythonDisplayFormatter(BaseFormatter): printer(obj) return True # Finally look for special method names - method = get_real_method(obj, self.print_method) + method = get_real_method(obj, self.print_method) if method is not None: method() return True @@ -1030,7 +1030,7 @@ def format_display_data(obj, include=None, exclude=None): """ from IPython.core.interactiveshell import InteractiveShell - return InteractiveShell.instance().display_formatter.format( + return InteractiveShell.instance().display_formatter.format( obj, include, exclude diff --git a/contrib/python/ipython/py2/IPython/core/history.py b/contrib/python/ipython/py2/IPython/core/history.py index 2e7fdbc845..1e8e227a50 100644 --- a/contrib/python/ipython/py2/IPython/core/history.py +++ b/contrib/python/ipython/py2/IPython/core/history.py @@ -1,8 +1,8 @@ """ History related magics and functionality """ -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + from __future__ import print_function import atexit @@ -18,16 +18,16 @@ except ImportError: sqlite3 = None import threading -from traitlets.config.configurable import LoggingConfigurable +from traitlets.config.configurable import LoggingConfigurable from decorator import decorator from IPython.utils.decorators import undoc from IPython.paths import locate_profile from IPython.utils import py3compat from traitlets import ( Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError, - default, observe, + default, observe, ) -from warnings import warn +from warnings import warn #----------------------------------------------------------------------------- # Classes and functions @@ -72,55 +72,55 @@ else: class OperationalError(Exception): "Dummy exception when sqlite could not be imported. Should never occur." -# use 16kB as threshold for whether a corrupt history db should be saved -# that should be at least 100 entries or so -_SAVE_DB_SIZE = 16384 - +# use 16kB as threshold for whether a corrupt history db should be saved +# that should be at least 100 entries or so +_SAVE_DB_SIZE = 16384 + @decorator def catch_corrupt_db(f, self, *a, **kw): """A decorator which wraps HistoryAccessor method calls to catch errors from a corrupt SQLite database, move the old database out of the way, and create a new one. - - We avoid clobbering larger databases because this may be triggered due to filesystem issues, - not just a corrupt file. + + We avoid clobbering larger databases because this may be triggered due to filesystem issues, + not just a corrupt file. """ try: return f(self, *a, **kw) - except (DatabaseError, OperationalError) as e: - self._corrupt_db_counter += 1 - self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e) - if self.hist_file != ':memory:': - if self._corrupt_db_counter > self._corrupt_db_limit: - self.hist_file = ':memory:' - self.log.error("Failed to load history too many times, history will not be saved.") - elif os.path.isfile(self.hist_file): - # move the file out of the way - base, ext = os.path.splitext(self.hist_file) - size = os.stat(self.hist_file).st_size - if size >= _SAVE_DB_SIZE: - # if there's significant content, avoid clobbering - now = datetime.datetime.now().isoformat().replace(':', '.') - newpath = base + '-corrupt-' + now + ext - # don't clobber previous corrupt backups - for i in range(100): - if not os.path.isfile(newpath): - break - else: - newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext - else: - # not much content, possibly empty; don't worry about clobbering - # maybe we should just delete it? - newpath = base + '-corrupt' + ext - os.rename(self.hist_file, newpath) - self.log.error("History file was moved to %s and a new file created.", newpath) + except (DatabaseError, OperationalError) as e: + self._corrupt_db_counter += 1 + self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e) + if self.hist_file != ':memory:': + if self._corrupt_db_counter > self._corrupt_db_limit: + self.hist_file = ':memory:' + self.log.error("Failed to load history too many times, history will not be saved.") + elif os.path.isfile(self.hist_file): + # move the file out of the way + base, ext = os.path.splitext(self.hist_file) + size = os.stat(self.hist_file).st_size + if size >= _SAVE_DB_SIZE: + # if there's significant content, avoid clobbering + now = datetime.datetime.now().isoformat().replace(':', '.') + newpath = base + '-corrupt-' + now + ext + # don't clobber previous corrupt backups + for i in range(100): + if not os.path.isfile(newpath): + break + else: + newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext + else: + # not much content, possibly empty; don't worry about clobbering + # maybe we should just delete it? + newpath = base + '-corrupt' + ext + os.rename(self.hist_file, newpath) + self.log.error("History file was moved to %s and a new file created.", newpath) self.init_db() return [] else: - # Failed with :memory:, something serious is wrong + # Failed with :memory:, something serious is wrong raise -class HistoryAccessorBase(LoggingConfigurable): +class HistoryAccessorBase(LoggingConfigurable): """An abstract class for History Accessors """ def get_tail(self, n=10, raw=True, output=False, include_latest=False): @@ -143,13 +143,13 @@ class HistoryAccessor(HistoryAccessorBase): This is intended for use by standalone history tools. IPython shells use HistoryManager, below, which is a subclass of this.""" - # counter for init_db retries, so we don't keep trying over and over - _corrupt_db_counter = 0 - # after two failures, fallback on :memory: - _corrupt_db_limit = 2 - + # counter for init_db retries, so we don't keep trying over and over + _corrupt_db_counter = 0 + # after two failures, fallback on :memory: + _corrupt_db_limit = 2 + # String holding the path to the history file - hist_file = Unicode( + hist_file = Unicode( help="""Path to file to use for SQLite history database. By default, IPython will put the history database in the IPython @@ -161,13 +161,13 @@ class HistoryAccessor(HistoryAccessorBase): local disk, e.g:: ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite - - you can also use the specific value `:memory:` (including the colon - at both end but not the back ticks), to avoid creating an history file. + + you can also use the specific value `:memory:` (including the colon + at both end but not the back ticks), to avoid creating an history file. - """).tag(config=True) + """).tag(config=True) - enabled = Bool(True, + enabled = Bool(True, help="""enable the SQLite history set enabled=False to disable the SQLite history, @@ -175,22 +175,22 @@ class HistoryAccessor(HistoryAccessorBase): and no background saving thread. This may be necessary in some threaded environments where IPython is embedded. """ - ).tag(config=True) + ).tag(config=True) - connection_options = Dict( + connection_options = Dict( help="""Options for configuring the SQLite connection These options are passed as keyword args to sqlite3.connect when establishing database conenctions. """ - ).tag(config=True) + ).tag(config=True) # The SQLite database db = Any() - @observe('db') - def _db_changed(self, change): + @observe('db') + def _db_changed(self, change): """validate the db, since it can be an Instance of two different types""" - new = change['new'] + new = change['new'] connection_types = (DummyDB,) if sqlite3 is not None: connection_types = (DummyDB, sqlite3.Connection) @@ -266,8 +266,8 @@ class HistoryAccessor(HistoryAccessorBase): (session integer, line integer, output text, PRIMARY KEY (session, line))""") self.db.commit() - # success! reset corrupt db count - self._corrupt_db_counter = 0 + # success! reset corrupt db count + self._corrupt_db_counter = 0 def writeout_cache(self): """Overridden by HistoryManager to dump the cache before certain @@ -486,7 +486,7 @@ class HistoryManager(HistoryAccessor): input_hist_raw = List([""]) # A list of directories visited during session dir_hist = List() - @default('dir_hist') + @default('dir_hist') def _dir_hist_default(self): try: return [py3compat.getcwd()] @@ -502,13 +502,13 @@ class HistoryManager(HistoryAccessor): # The number of the current session in the history database session_number = Integer() - db_log_output = Bool(False, + db_log_output = Bool(False, help="Should the history database include output? (default: no)" - ).tag(config=True) - db_cache_size = Integer(0, + ).tag(config=True) + db_cache_size = Integer(0, help="Write to database every x commands (higher values save disk access & power).\n" "Values of 1 or less effectively disable caching." - ).tag(config=True) + ).tag(config=True) # The input and output caches db_input_cache = List() db_output_cache = List() diff --git a/contrib/python/ipython/py2/IPython/core/historyapp.py b/contrib/python/ipython/py2/IPython/core/historyapp.py index d51426d2ca..d083a78822 100644 --- a/contrib/python/ipython/py2/IPython/core/historyapp.py +++ b/contrib/python/ipython/py2/IPython/core/historyapp.py @@ -34,17 +34,17 @@ This is an handy alias to `ipython history trim --keep=0` class HistoryTrim(BaseIPythonApplication): description = trim_hist_help - backup = Bool(False, - help="Keep the old history file as history.sqlite.<N>" - ).tag(config=True) + backup = Bool(False, + help="Keep the old history file as history.sqlite.<N>" + ).tag(config=True) - keep = Int(1000, - help="Number of recent lines to keep in the database." - ).tag(config=True) + keep = Int(1000, + help="Number of recent lines to keep in the database." + ).tag(config=True) flags = Dict(dict( backup = ({'HistoryTrim' : {'backup' : True}}, - backup.help + backup.help ) )) @@ -120,18 +120,18 @@ class HistoryTrim(BaseIPythonApplication): class HistoryClear(HistoryTrim): description = clear_hist_help - keep = Int(0, + keep = Int(0, help="Number of recent lines to keep in the database.") - force = Bool(False, - help="Don't prompt user for confirmation" - ).tag(config=True) + force = Bool(False, + help="Don't prompt user for confirmation" + ).tag(config=True) flags = Dict(dict( force = ({'HistoryClear' : {'force' : True}}, - force.help), + force.help), f = ({'HistoryTrim' : {'force' : True}}, - force.help + force.help ) )) aliases = Dict() diff --git a/contrib/python/ipython/py2/IPython/core/hooks.py b/contrib/python/ipython/py2/IPython/core/hooks.py index e6fc84087f..a93bc31627 100644 --- a/contrib/python/ipython/py2/IPython/core/hooks.py +++ b/contrib/python/ipython/py2/IPython/core/hooks.py @@ -37,7 +37,7 @@ example, you could use a startup file like this:: import os import subprocess -import warnings +import warnings import sys from IPython.core.error import TryNext @@ -84,24 +84,24 @@ def editor(self, filename, linenum=None, wait=True): import tempfile def fix_error_editor(self,filename,linenum,column,msg): - """DEPRECATED - - Open the editor at the given filename, linenumber, column and + """DEPRECATED + + Open the editor at the given filename, linenumber, column and show an error message. This is used for correcting syntax errors. The current implementation only has special support for the VIM editor, and falls back on the 'editor' hook if VIM is not used. - Call ip.set_hook('fix_error_editor',yourfunc) to use your own function, + Call ip.set_hook('fix_error_editor',yourfunc) to use your own function, """ - - warnings.warn(""" -`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed -in future versions. It appears to be used only for automatically fixing syntax -error that has been broken for a few years and has thus been removed. If you -happend to use this function and still need it please make your voice heard on + + warnings.warn(""" +`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed +in future versions. It appears to be used only for automatically fixing syntax +error that has been broken for a few years and has thus been removed. If you +happend to use this function and still need it please make your voice heard on the mailing list ipython-dev@python.org , or on the GitHub Issue tracker: -https://github.com/ipython/ipython/issues/9649 """, UserWarning) - +https://github.com/ipython/ipython/issues/9649 """, UserWarning) + def vim_quickfix_file(): t = tempfile.NamedTemporaryFile() t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) diff --git a/contrib/python/ipython/py2/IPython/core/interactiveshell.py b/contrib/python/ipython/py2/IPython/core/interactiveshell.py index ad8824b606..67b84a6e5f 100644 --- a/contrib/python/ipython/py2/IPython/core/interactiveshell.py +++ b/contrib/python/ipython/py2/IPython/core/interactiveshell.py @@ -31,7 +31,7 @@ from io import open as io_open from pickleshare import PickleShareDB from traitlets.config.configurable import SingletonConfigurable -from IPython.core import oinspect +from IPython.core import oinspect from IPython.core import magic from IPython.core import page from IPython.core import prefilter @@ -42,7 +42,7 @@ from IPython.core.autocall import ExitAutocall from IPython.core.builtin_trap import BuiltinTrap from IPython.core.events import EventManager, available_events from IPython.core.compilerop import CachingCompiler, check_linecache_ipython -from IPython.core.debugger import Pdb +from IPython.core.debugger import Pdb from IPython.core.display_trap import DisplayTrap from IPython.core.displayhook import DisplayHook from IPython.core.displaypub import DisplayPublisher @@ -50,14 +50,14 @@ from IPython.core.error import InputRejected, UsageError from IPython.core.extensions import ExtensionManager from IPython.core.formatters import DisplayFormatter from IPython.core.history import HistoryManager -from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 +from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 from IPython.core.logger import Logger from IPython.core.macro import Macro from IPython.core.payload import PayloadManager from IPython.core.prefilter import PrefilterManager from IPython.core.profiledir import ProfileDir from IPython.core.usage import default_banner -from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest +from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest from IPython.display import display from IPython.utils import PyColorize from IPython.utils import io @@ -67,45 +67,45 @@ from IPython.utils.decorators import undoc from IPython.utils.io import ask_yes_no 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.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.strdispatch import StrDispatch from IPython.utils.syspathcontext import prepended_to_syspath -from IPython.utils.text import format_screen, LSString, SList, DollarFormatter -from IPython.utils.tempdir import TemporaryDirectory -from traitlets import ( - Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, - observe, default, -) -from warnings import warn -from logging import error +from IPython.utils.text import format_screen, LSString, SList, DollarFormatter +from IPython.utils.tempdir import TemporaryDirectory +from traitlets import ( + Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, + observe, default, +) +from warnings import warn +from logging import error import IPython.core.hooks -# NoOpContext is deprecated, but ipykernel imports it from here. -# See https://github.com/ipython/ipykernel/issues/157 -from IPython.utils.contexts import NoOpContext - -try: - import docrepr.sphinxify as sphx - - def sphinxify(doc): - with TemporaryDirectory() as dirname: - return { - 'text/html': sphx.sphinxify(doc, dirname), - 'text/plain': doc - } -except ImportError: - sphinxify = None - - -class ProvisionalWarning(DeprecationWarning): - """ - Warning class for unstable features - """ - pass - +# NoOpContext is deprecated, but ipykernel imports it from here. +# See https://github.com/ipython/ipykernel/issues/157 +from IPython.utils.contexts import NoOpContext + +try: + import docrepr.sphinxify as sphx + + def sphinxify(doc): + with TemporaryDirectory() as dirname: + return { + 'text/html': sphx.sphinxify(doc, dirname), + 'text/plain': doc + } +except ImportError: + sphinxify = None + + +class ProvisionalWarning(DeprecationWarning): + """ + Warning class for unstable features + """ + pass + #----------------------------------------------------------------------------- # Globals #----------------------------------------------------------------------------- @@ -141,10 +141,10 @@ class SpaceInInput(Exception): pass def get_default_colors(): - "DEPRECATED" - warn('get_default_color is Deprecated, and is `Neutral` on all platforms.', - DeprecationWarning, stacklevel=2) - return 'Neutral' + "DEPRECATED" + warn('get_default_color is Deprecated, and is `Neutral` on all platforms.', + DeprecationWarning, stacklevel=2) + return 'Neutral' class SeparateUnicode(Unicode): @@ -187,28 +187,28 @@ class ExecutionResult(object): if self.error_in_exec is not None: raise self.error_in_exec - def __repr__(self): - if sys.version_info > (3,): - name = self.__class__.__qualname__ - else: - name = self.__class__.__name__ - return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ - (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) - + def __repr__(self): + if sys.version_info > (3,): + name = self.__class__.__qualname__ + else: + name = self.__class__.__name__ + return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ + (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) + class InteractiveShell(SingletonConfigurable): """An enhanced, interactive shell for Python.""" _instance = None - - ast_transformers = List([], help= + + ast_transformers = List([], help= """ A list of ast.NodeTransformer subclass instances, which will be applied to user input before code is run. """ - ).tag(config=True) + ).tag(config=True) - autocall = Enum((0,1,2), default_value=0, help= + autocall = Enum((0,1,2), default_value=0, help= """ Make IPython automatically call any callable object even if you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)' @@ -217,29 +217,29 @@ class InteractiveShell(SingletonConfigurable): arguments on the line, and '2' for 'full' autocall, where all callable objects are automatically called (even if no arguments are present). """ - ).tag(config=True) + ).tag(config=True) # TODO: remove all autoindent logic and put into frontends. # We can't do this yet because even runlines uses the autoindent. - autoindent = Bool(True, help= + autoindent = Bool(True, help= """ Autoindent IPython code entered interactively. """ - ).tag(config=True) - - automagic = Bool(True, help= + ).tag(config=True) + + automagic = Bool(True, help= """ Enable magic commands to be called without the leading %. """ - ).tag(config=True) - - banner1 = Unicode(default_banner, + ).tag(config=True) + + banner1 = Unicode(default_banner, help="""The part of the banner to be printed before the profile""" - ).tag(config=True) - banner2 = Unicode('', + ).tag(config=True) + banner2 = Unicode('', help="""The part of the banner to be printed after the profile""" - ).tag(config=True) + ).tag(config=True) - cache_size = Integer(1000, help= + cache_size = Integer(1000, help= """ Set the size of the output cache. The default is 1000, you can change it permanently in your config file. Setting it to 0 completely @@ -248,20 +248,20 @@ class InteractiveShell(SingletonConfigurable): issued). This limit is defined because otherwise you'll spend more time re-flushing a too small cache than working """ - ).tag(config=True) - color_info = Bool(True, help= + ).tag(config=True) + color_info = Bool(True, help= """ Use colors for displaying information about objects. Because this information is passed through a pager (like 'less'), and some pagers get confused with color codes, this capability can be turned off. """ - ).tag(config=True) - colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), - default_value='Neutral', - help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." - ).tag(config=True) - debug = Bool(False).tag(config=True) - deep_reload = Bool(False, help= + ).tag(config=True) + colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), + default_value='Neutral', + help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." + ).tag(config=True) + debug = Bool(False).tag(config=True) + deep_reload = Bool(False, help= """ **Deprecated** @@ -275,47 +275,47 @@ class InteractiveShell(SingletonConfigurable): deep_reload is off, IPython will use the normal reload(), but deep_reload will still be available as dreload(). """ - ).tag(config=True) - disable_failing_post_execute = Bool(False, + ).tag(config=True) + disable_failing_post_execute = Bool(False, help="Don't call post-execute functions that have failed in the past." - ).tag(config=True) + ).tag(config=True) display_formatter = Instance(DisplayFormatter, allow_none=True) displayhook_class = Type(DisplayHook) display_pub_class = Type(DisplayPublisher) - - sphinxify_docstring = Bool(False, help= - """ - Enables rich html representation of docstrings. (This requires the - docrepr module). - """).tag(config=True) - - @observe("sphinxify_docstring") - def _sphinxify_docstring_changed(self, change): - if change['new']: - warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) - - enable_html_pager = Bool(False, help= - """ - (Provisional API) enables html representation in mime bundles sent - to pagers. - """).tag(config=True) - - @observe("enable_html_pager") - def _enable_html_pager_changed(self, change): - if change['new']: - warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) - + + sphinxify_docstring = Bool(False, help= + """ + Enables rich html representation of docstrings. (This requires the + docrepr module). + """).tag(config=True) + + @observe("sphinxify_docstring") + def _sphinxify_docstring_changed(self, change): + if change['new']: + warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) + + enable_html_pager = Bool(False, help= + """ + (Provisional API) enables html representation in mime bundles sent + to pagers. + """).tag(config=True) + + @observe("enable_html_pager") + def _enable_html_pager_changed(self, change): + if change['new']: + warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) + data_pub_class = None - exit_now = Bool(False) + exit_now = Bool(False) exiter = Instance(ExitAutocall) - @default('exiter') + @default('exiter') def _exiter_default(self): return ExitAutocall(self) # Monotonically increasing execution counter execution_count = Integer(1) filename = Unicode("<ipython console>") - ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ + ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ # Input splitter, to transform input line by line and detect when a block # is ready to be executed. @@ -327,90 +327,90 @@ class InteractiveShell(SingletonConfigurable): input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', (), {'line_input_checker': False}) - logstart = Bool(False, help= + logstart = Bool(False, help= """ Start logging to the default log file in overwrite mode. Use `logappend` to specify a log file to **append** logs to. """ - ).tag(config=True) - logfile = Unicode('', help= + ).tag(config=True) + logfile = Unicode('', help= """ The name of the logfile to use. """ - ).tag(config=True) - logappend = Unicode('', help= + ).tag(config=True) + logappend = Unicode('', help= """ Start logging to the given file in append mode. Use `logfile` to specify a log file to **overwrite** logs to. """ - ).tag(config=True) + ).tag(config=True) object_info_string_level = Enum((0,1,2), default_value=0, - ).tag(config=True) - pdb = Bool(False, help= + ).tag(config=True) + pdb = Bool(False, help= """ Automatically call the pdb debugger after every exception. """ - ).tag(config=True) - display_page = Bool(False, + ).tag(config=True) + display_page = Bool(False, help="""If True, anything that would be passed to the pager will be displayed as regular output instead.""" - ).tag(config=True) + ).tag(config=True) # deprecated prompt traits: - - prompt_in1 = Unicode('In [\\#]: ', - help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." - ).tag(config=True) - prompt_in2 = Unicode(' .\\D.: ', - help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." - ).tag(config=True) - prompt_out = Unicode('Out[\\#]: ', - help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." - ).tag(config=True) - prompts_pad_left = Bool(True, - help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." - ).tag(config=True) - - @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') - def _prompt_trait_changed(self, change): - name = change['name'] - warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format( - name=name) + + prompt_in1 = Unicode('In [\\#]: ', + help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." + ).tag(config=True) + prompt_in2 = Unicode(' .\\D.: ', + help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." + ).tag(config=True) + prompt_out = Unicode('Out[\\#]: ', + help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." + ).tag(config=True) + prompts_pad_left = Bool(True, + help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." + ).tag(config=True) + + @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') + def _prompt_trait_changed(self, change): + name = change['name'] + warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format( + name=name) ) # protect against weird cases where self.config may not exist: - show_rewritten_input = Bool(True, + show_rewritten_input = Bool(True, help="Show rewritten input, e.g. for autocall." - ).tag(config=True) + ).tag(config=True) - quiet = Bool(False).tag(config=True) + quiet = Bool(False).tag(config=True) - history_length = Integer(10000, - help='Total length of command history' - ).tag(config=True) + history_length = Integer(10000, + help='Total length of command history' + ).tag(config=True) - history_load_length = Integer(1000, help= + history_load_length = Integer(1000, help= """ The number of saved history entries to be loaded - into the history buffer at startup. + into the history buffer at startup. """ - ).tag(config=True) + ).tag(config=True) ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], - default_value='last_expr', + default_value='last_expr', help=""" 'all', 'last', 'last_expr' or 'none', specifying which nodes should be - run interactively (displaying output from expressions).""" - ).tag(config=True) + run interactively (displaying output from expressions).""" + ).tag(config=True) # TODO: this part of prompt management should be moved to the frontends. # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' - separate_in = SeparateUnicode('\n').tag(config=True) - separate_out = SeparateUnicode('').tag(config=True) - separate_out2 = SeparateUnicode('').tag(config=True) - wildcards_case_sensitive = Bool(True).tag(config=True) + separate_in = SeparateUnicode('\n').tag(config=True) + separate_out = SeparateUnicode('').tag(config=True) + separate_out2 = SeparateUnicode('').tag(config=True) + wildcards_case_sensitive = Bool(True).tag(config=True) xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), - default_value='Context').tag(config=True) + default_value='Context').tag(config=True) # Subcomponents of InteractiveShell alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) @@ -436,8 +436,8 @@ class InteractiveShell(SingletonConfigurable): # Tracks any GUI loop loaded for pylab pylab_gui_select = None - last_execution_succeeded = Bool(True, help='Did last executed command succeeded') - + last_execution_succeeded = Bool(True, help='Did last executed command succeeded') + def __init__(self, ipython_dir=None, profile_dir=None, user_module=None, user_ns=None, custom_exceptions=((), None), **kwargs): @@ -445,9 +445,9 @@ class InteractiveShell(SingletonConfigurable): # This is where traits with a config_key argument are updated # from the values on config. super(InteractiveShell, self).__init__(**kwargs) - if 'PromptManager' in self.config: - warn('As of IPython 5.0 `PromptManager` config will have no effect' - ' and has been replaced by TerminalInteractiveShell.prompts_class') + if 'PromptManager' in self.config: + warn('As of IPython 5.0 `PromptManager` config will have no effect' + ' and has been replaced by TerminalInteractiveShell.prompts_class') self.configurables = [self] # These are relatively independent and stateless @@ -455,7 +455,7 @@ class InteractiveShell(SingletonConfigurable): self.init_profile_dir(profile_dir) self.init_instance_attrs() self.init_environment() - + # Check if we're in a virtualenv, and set up sys.path. self.init_virtualenv() @@ -522,12 +522,12 @@ class InteractiveShell(SingletonConfigurable): #------------------------------------------------------------------------- # Trait changed handlers #------------------------------------------------------------------------- - @observe('ipython_dir') - def _ipython_dir_changed(self, change): - ensure_dir_exists(change['new']) + @observe('ipython_dir') + def _ipython_dir_changed(self, change): + ensure_dir_exists(change['new']) def set_autoindent(self,value=None): - """Set the autoindent flag. + """Set the autoindent flag. If called with no arguments, it acts as a toggle.""" if value is None: @@ -598,10 +598,10 @@ class InteractiveShell(SingletonConfigurable): pyformat = PyColorize.Parser().format self.pycolorize = lambda src: pyformat(src,'str',self.colors) - def refresh_style(self): - # No-op here, used in subclass - pass - + def refresh_style(self): + # No-op here, used in subclass + pass + def init_pushd_popd_magic(self): # for pushd/popd management self.home_dir = get_home_dir() @@ -653,10 +653,10 @@ class InteractiveShell(SingletonConfigurable): # override sys.stdout and sys.stderr themselves, you need to do that # *before* instantiating this class, because io holds onto # references to the underlying streams. - # io.std* are deprecated, but don't show our own deprecation warnings - # during initialization of the deprecated API. - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) + # io.std* are deprecated, but don't show our own deprecation warnings + # during initialization of the deprecated API. + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) io.stdout = io.IOStream(sys.stdout) io.stderr = io.IOStream(sys.stderr) @@ -700,15 +700,15 @@ class InteractiveShell(SingletonConfigurable): virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. - + Adapted from code snippets online. - + http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv """ if 'VIRTUAL_ENV' not in os.environ: # Not in a virtualenv return - + # venv detection: # stdlib venv may symlink sys.executable, so we can't use realpath. # but others can symlink *to* the venv Python, so we can't just use sys.executable. @@ -722,15 +722,15 @@ class InteractiveShell(SingletonConfigurable): if any(p.startswith(p_venv) for p in paths): # Running properly in the virtualenv, don't need to do anything return - + warn("Attempting to work in a virtualenv. If you encounter problems, please " "install IPython inside the virtualenv.") if sys.platform == "win32": - virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') + virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') else: virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', 'python%d.%d' % sys.version_info[:2], 'site-packages') - + import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env) @@ -765,7 +765,7 @@ class InteractiveShell(SingletonConfigurable): #------------------------------------------------------------------------- # Things related to the banner #------------------------------------------------------------------------- - + @property def banner(self): banner = self.banner1 @@ -778,8 +778,8 @@ class InteractiveShell(SingletonConfigurable): def show_banner(self, banner=None): if banner is None: banner = self.banner - sys.stdout.write(banner) - + sys.stdout.write(banner) + #------------------------------------------------------------------------- # Things related to hooks #------------------------------------------------------------------------- @@ -796,10 +796,10 @@ class InteractiveShell(SingletonConfigurable): # default hooks have priority 100, i.e. low; user hooks should have # 0-100 priority self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) - + if self.display_page: self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) - + def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, _warn_deprecated=True): """set_hook(name,hook) -> sets an internal IPython hook. @@ -857,13 +857,13 @@ class InteractiveShell(SingletonConfigurable): def register_post_execute(self, func): """DEPRECATED: Use ip.events.register('post_run_cell', func) - + Register a function for calling after code execution. """ warn("ip.register_post_execute is deprecated, use " "ip.events.register('post_run_cell', func) instead.") self.events.register('post_run_cell', func) - + def _clear_warning_registry(self): # clear the warning registry, so that different code blocks with # overlapping line number ranges don't cause spurious suppression of @@ -877,14 +877,14 @@ class InteractiveShell(SingletonConfigurable): def new_main_mod(self, filename, modname): """Return a new 'main' module object for user code execution. - + ``filename`` should be the path of the script which will be run in the module. Requests with the same filename will get the same module, with its namespace cleared. - + ``modname`` should be the module name - normally either '__main__' or the basename of the file without the extension. - + When scripts are executed via %run, we must keep a reference to their __main__ module around so that Python doesn't clear it, rendering references to module globals useless. @@ -905,12 +905,12 @@ class InteractiveShell(SingletonConfigurable): else: main_mod.__dict__.clear() main_mod.__name__ = modname - + main_mod.__file__ = filename # It seems pydoc (and perhaps others) needs any module instance to # implement a __nonzero__ method main_mod.__nonzero__ = lambda : True - + return main_mod def clear_main_mod_cache(self): @@ -962,7 +962,7 @@ class InteractiveShell(SingletonConfigurable): 'Control auto-activation of pdb at exceptions') def debugger(self,force=False): - """Call the pdb debugger. + """Call the pdb debugger. Keywords: @@ -979,7 +979,7 @@ class InteractiveShell(SingletonConfigurable): error('No traceback has been produced, nothing to debug.') return - self.InteractiveTB.debugger(force=True) + self.InteractiveTB.debugger(force=True) #------------------------------------------------------------------------- # Things related to IPython's various namespaces @@ -1063,17 +1063,17 @@ class InteractiveShell(SingletonConfigurable): 'user_local':self.user_ns, 'builtin':builtin_mod.__dict__ } - + @property def user_global_ns(self): return self.user_module.__dict__ def prepare_user_module(self, user_module=None, user_ns=None): """Prepare the module and namespace in which user code will be run. - + When IPython is started normally, both parameters are None: a new module is created automatically, and its __dict__ used as the namespace. - + If only user_module is provided, its __dict__ is used as the namespace. If only user_ns is provided, a dummy module is created, and user_ns becomes the global namespace. If both are provided (as they may be @@ -1096,17 +1096,17 @@ class InteractiveShell(SingletonConfigurable): user_ns.setdefault("__name__", "__main__") user_module = DummyMod() user_module.__dict__ = user_ns - + if user_module is None: user_module = types.ModuleType("__main__", doc="Automatically created module for IPython interactive environment") - + # We must ensure that __builtin__ (without the final 's') is always # available and pointing to the __builtin__ *module*. For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html user_module.__dict__.setdefault('__builtin__', builtin_mod) user_module.__dict__.setdefault('__builtins__', builtin_mod) - + if user_ns is None: user_ns = user_module.__dict__ @@ -1162,7 +1162,7 @@ class InteractiveShell(SingletonConfigurable): # For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html ns = dict() - + # make global variables for user access to the histories ns['_ih'] = self.history_manager.input_hist_parsed ns['_oh'] = self.history_manager.output_hist @@ -1177,7 +1177,7 @@ class InteractiveShell(SingletonConfigurable): # Store myself as the public api!!! ns['get_ipython'] = self.get_ipython - + ns['exit'] = self.exiter ns['quit'] = self.exiter @@ -1191,12 +1191,12 @@ class InteractiveShell(SingletonConfigurable): # Finally, update the real user's namespace self.user_ns.update(ns) - + @property def all_ns_refs(self): """Get a list of references to all the namespace dictionaries in which IPython might store a user-created object. - + Note that this does not include the displayhook, which also caches objects from the output.""" return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ @@ -1230,9 +1230,9 @@ class InteractiveShell(SingletonConfigurable): drop_keys.discard('__name__') for k in drop_keys: del ns[k] - + self.user_ns_hidden.clear() - + # Restore the user namespaces to minimal usability self.init_user_ns() @@ -1261,7 +1261,7 @@ class InteractiveShell(SingletonConfigurable): raise ValueError("Refusing to delete %s" % varname) ns_refs = self.all_ns_refs - + if by_name: # Delete by name for ns in ns_refs: try: @@ -1358,11 +1358,11 @@ class InteractiveShell(SingletonConfigurable): def drop_by_id(self, variables): """Remove a dict of variables from the user namespace, if they are the same as the values in the dictionary. - + This is intended for use by extensions: variables that they've added can be taken back out if they are unloaded, without removing any that the user has overwritten. - + Parameters ---------- variables : dict @@ -1520,20 +1520,20 @@ class InteractiveShell(SingletonConfigurable): def _inspect(self, meth, oname, namespaces=None, **kw): """Generic interface to the inspector system. - This function is meant to be called by pdef, pdoc & friends. - """ + This function is meant to be called by pdef, pdoc & friends. + """ info = self._object_find(oname, namespaces) - docformat = sphinxify if self.sphinxify_docstring else None + docformat = sphinxify if self.sphinxify_docstring else None if info.found: pmethod = getattr(self.inspector, meth) - # TODO: only apply format_screen to the plain/text repr of the mime - # bundle. - formatter = format_screen if info.ismagic else docformat + # TODO: only apply format_screen to the plain/text repr of the mime + # bundle. + formatter = format_screen if info.ismagic else docformat if meth == 'pdoc': pmethod(info.obj, oname, formatter) elif meth == 'pinfo': - pmethod(info.obj, oname, formatter, info, - enable_html_pager=self.enable_html_pager, **kw) + pmethod(info.obj, oname, formatter, info, + enable_html_pager=self.enable_html_pager, **kw) else: pmethod(info.obj, oname) else: @@ -1553,18 +1553,18 @@ class InteractiveShell(SingletonConfigurable): def object_inspect_text(self, oname, detail_level=0): """Get object info as formatted text""" - return self.object_inspect_mime(oname, detail_level)['text/plain'] - - def object_inspect_mime(self, oname, detail_level=0): - """Get object info as a mimebundle of formatted representations. - - A mimebundle is a dictionary, keyed by mime-type. - It must always have the key `'text/plain'`. - """ + return self.object_inspect_mime(oname, detail_level)['text/plain'] + + def object_inspect_mime(self, oname, detail_level=0): + """Get object info as a mimebundle of formatted representations. + + A mimebundle is a dictionary, keyed by mime-type. + It must always have the key `'text/plain'`. + """ with self.builtin_trap: info = self._object_find(oname) if info.found: - return self.inspector._get_info(info.obj, oname, info=info, + return self.inspector._get_info(info.obj, oname, info=info, detail_level=detail_level ) else: @@ -1583,8 +1583,8 @@ class InteractiveShell(SingletonConfigurable): # Things related to exception handling and tracebacks (not debugging) #------------------------------------------------------------------------- - debugger_cls = Pdb - + debugger_cls = Pdb + def init_traceback_handlers(self, custom_exceptions): # Syntax error handler. self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') @@ -1595,8 +1595,8 @@ class InteractiveShell(SingletonConfigurable): self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', color_scheme='NoColor', tb_offset = 1, - check_cache=check_linecache_ipython, - debugger_cls=self.debugger_cls) + check_cache=check_linecache_ipython, + debugger_cls=self.debugger_cls) # The instance will store a pointer to the system-wide exception hook, # so that runtime code (such as magics) can access it. This is because @@ -1610,7 +1610,7 @@ class InteractiveShell(SingletonConfigurable): self.InteractiveTB.set_mode(mode=self.xmode) def set_custom_exc(self, exc_tuple, handler): - """set_custom_exc(exc_tuple, handler) + """set_custom_exc(exc_tuple, handler) Set a custom exception handler, which will be called if any of the exceptions in exc_tuple occur in the mainloop (specifically, in the @@ -1653,19 +1653,19 @@ class InteractiveShell(SingletonConfigurable): assert type(exc_tuple)==type(()) , \ "The custom exceptions must be given AS A TUPLE." - def dummy_handler(self, etype, value, tb, tb_offset=None): + def dummy_handler(self, etype, value, tb, tb_offset=None): print('*** Simple custom exception handler ***') print('Exception type :',etype) print('Exception value:',value) print('Traceback :',tb) #print 'Source code :','\n'.join(self.buffer) - + def validate_stb(stb): """validate structured traceback return type - + return type of CustomTB *should* be a list of strings, but allow single strings or None, which are harmless. - + This function will *always* return a list of strings, and will raise a TypeError if stb is inappropriate. """ @@ -1688,7 +1688,7 @@ class InteractiveShell(SingletonConfigurable): else: def wrapped(self,etype,value,tb,tb_offset=None): """wrap CustomTB handler, to protect IPython from user code - + This makes it harder (but not impossible) for custom exception handlers to crash IPython. """ @@ -1698,11 +1698,11 @@ class InteractiveShell(SingletonConfigurable): except: # clear custom handler immediately self.set_custom_exc((), None) - print("Custom TB Handler failed, unregistering", file=sys.stderr) + print("Custom TB Handler failed, unregistering", file=sys.stderr) # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) - print(self.InteractiveTB.stb2text(stb)) - print("The original exception:") + print(self.InteractiveTB.stb2text(stb)) + print("The original exception:") stb = self.InteractiveTB.structured_traceback( (etype,value,tb), tb_offset=tb_offset ) @@ -1737,10 +1737,10 @@ class InteractiveShell(SingletonConfigurable): def _get_exc_info(self, exc_tuple=None): """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. - + Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. - + raises ValueError if none of these contain any information """ if exc_tuple is None: @@ -1752,10 +1752,10 @@ class InteractiveShell(SingletonConfigurable): if hasattr(sys, 'last_type'): etype, value, tb = sys.last_type, sys.last_value, \ sys.last_traceback - + if etype is None: raise ValueError("No exception to find") - + # Now store the exception info in sys.last_type etc. # WARNING: these variables are somewhat deprecated and not # necessarily safe to use in a threaded environment, but tools @@ -1764,16 +1764,16 @@ class InteractiveShell(SingletonConfigurable): sys.last_type = etype sys.last_value = value sys.last_traceback = tb - + return etype, value, tb - + def show_usage_error(self, exc): """Show a short message for UsageErrors - + These are special exceptions that shouldn't show a traceback. """ - print("UsageError: %s" % exc, file=sys.stderr) - + print("UsageError: %s" % exc, file=sys.stderr) + def get_exception_only(self, exc_tuple=None): """ Return as a string (ending with a newline) the exception that @@ -1800,9 +1800,9 @@ class InteractiveShell(SingletonConfigurable): try: etype, value, tb = self._get_exc_info(exc_tuple) except ValueError: - print('No traceback available to show.', file=sys.stderr) + print('No traceback available to show.', file=sys.stderr) return - + if issubclass(etype, SyntaxError): # Though this won't be called by syntax errors in the input # line, there may be SyntaxError cases with imported code. @@ -1835,7 +1835,7 @@ class InteractiveShell(SingletonConfigurable): self._showtraceback(etype, value, stb) except KeyboardInterrupt: - print('\n' + self.get_exception_only(), file=sys.stderr) + print('\n' + self.get_exception_only(), file=sys.stderr) def _showtraceback(self, etype, evalue, stb): """Actually show a traceback. @@ -1843,7 +1843,7 @@ class InteractiveShell(SingletonConfigurable): Subclasses may override this method to put the traceback on a different place, like a side channel. """ - print(self.InteractiveTB.stb2text(stb)) + print(self.InteractiveTB.stb2text(stb)) def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. @@ -1862,7 +1862,7 @@ class InteractiveShell(SingletonConfigurable): except: # Not the format we expect; leave it alone pass - + stb = self.SyntaxTB.structured_traceback(etype, value, []) self._showtraceback(etype, value, stb) @@ -1881,12 +1881,12 @@ class InteractiveShell(SingletonConfigurable): #------------------------------------------------------------------------- def init_readline(self): - """DEPRECATED - - Moved to terminal subclass, here only to simplify the init logic.""" + """DEPRECATED + + Moved to terminal subclass, here only to simplify the init logic.""" # Set a number of methods that depend on readline to be no-op - warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', - DeprecationWarning, stacklevel=2) + warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', + DeprecationWarning, stacklevel=2) self.set_custom_completer = no_op @skip_doctest @@ -1923,7 +1923,7 @@ class InteractiveShell(SingletonConfigurable): self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, - use_readline=False, + use_readline=False, parent=self, ) self.configurables.append(self.Completer) @@ -1941,7 +1941,7 @@ class InteractiveShell(SingletonConfigurable): self.set_hook('complete_command', reset_completer, str_key = '%reset') - @skip_doctest_py2 + @skip_doctest_py2 def complete(self, text, line=None, cursor_pos=None): """Return the completed text and a list of completions. @@ -2020,7 +2020,7 @@ class InteractiveShell(SingletonConfigurable): self.register_magics = self.magics_manager.register self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, - m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, + m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, ) @@ -2040,11 +2040,11 @@ class InteractiveShell(SingletonConfigurable): # should be split into a prompt manager and displayhook. We probably # even need a centralize colors management object. self.magic('colors %s' % self.colors) - + # Defined here so that it's included in the documentation @functools.wraps(magic.MagicsManager.register_function) def register_magic_function(self, func, magic_kind='line', magic_name=None): - self.magics_manager.register_function(func, + self.magics_manager.register_function(func, magic_kind=magic_kind, magic_name=magic_name) def run_line_magic(self, magic_name, line): @@ -2083,7 +2083,7 @@ class InteractiveShell(SingletonConfigurable): def run_cell_magic(self, magic_name, line, cell): """Execute the given cell magic. - + Parameters ---------- magic_name : str @@ -2230,7 +2230,7 @@ class InteractiveShell(SingletonConfigurable): try: ec = os.system(cmd) except KeyboardInterrupt: - print('\n' + self.get_exception_only(), file=sys.stderr) + print('\n' + self.get_exception_only(), file=sys.stderr) ec = -2 else: cmd = py3compat.unicode_to_str(cmd) @@ -2249,11 +2249,11 @@ class InteractiveShell(SingletonConfigurable): ec = subprocess.call(cmd, shell=True, executable=executable) except KeyboardInterrupt: # intercept control-C; a long traceback is not useful here - print('\n' + self.get_exception_only(), file=sys.stderr) + print('\n' + self.get_exception_only(), file=sys.stderr) ec = 130 if ec > 128: ec = -(ec - 128) - + # We explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. Note the semantics @@ -2316,7 +2316,7 @@ class InteractiveShell(SingletonConfigurable): def init_payload(self): self.payload_manager = PayloadManager(parent=self) self.configurables.append(self.payload_manager) - + #------------------------------------------------------------------------- # Things related to the prefilter #------------------------------------------------------------------------- @@ -2347,8 +2347,8 @@ class InteractiveShell(SingletonConfigurable): if not self.show_rewritten_input: return - # This is overridden in TerminalInteractiveShell to use fancy prompts - print("------> " + cmd) + # This is overridden in TerminalInteractiveShell to use fancy prompts + print("------> " + cmd) #------------------------------------------------------------------------- # Things related to extracting values/expressions from kernel and user_ns @@ -2356,13 +2356,13 @@ class InteractiveShell(SingletonConfigurable): def _user_obj_error(self): """return simple exception dict - + for use in user_expressions """ - + etype, evalue, tb = self._get_exc_info() stb = self.InteractiveTB.get_exception_only(etype, evalue) - + exc_info = { u'status' : 'error', u'traceback' : stb, @@ -2371,13 +2371,13 @@ class InteractiveShell(SingletonConfigurable): } return exc_info - + def _format_user_obj(self, obj): """format a user object to display dict - + for use in user_expressions """ - + data, md = self.display_formatter.format(obj) value = { 'status' : 'ok', @@ -2385,7 +2385,7 @@ class InteractiveShell(SingletonConfigurable): 'metadata' : md, } return value - + def user_expressions(self, expressions): """Evaluate a dict of expressions in the user's namespace. @@ -2404,7 +2404,7 @@ class InteractiveShell(SingletonConfigurable): out = {} user_ns = self.user_ns global_ns = self.user_global_ns - + for key, expr in iteritems(expressions): try: value = self._format_user_obj(eval(expr, global_ns, user_ns)) @@ -2475,7 +2475,7 @@ class InteractiveShell(SingletonConfigurable): # Python inserts the script's directory into sys.path dname = os.path.dirname(fname) - with prepended_to_syspath(dname), self.builtin_trap: + with prepended_to_syspath(dname), self.builtin_trap: try: glob, loc = (where + (None, ))[:2] py3compat.execfile( @@ -2532,7 +2532,7 @@ class InteractiveShell(SingletonConfigurable): # behavior of running a script from the system command line, where # Python inserts the script's directory into sys.path dname = os.path.dirname(fname) - + def get_cells(): """generator for sequence of code blocks to run""" if fname.endswith('.ipynb'): @@ -2616,9 +2616,9 @@ class InteractiveShell(SingletonConfigurable): result = ExecutionResult() if (not raw_cell) or raw_cell.isspace(): - self.last_execution_succeeded = True + self.last_execution_succeeded = True return result - + if silent: store_history = False @@ -2629,7 +2629,7 @@ class InteractiveShell(SingletonConfigurable): if store_history: self.execution_count += 1 result.error_before_exec = value - self.last_execution_succeeded = False + self.last_execution_succeeded = False return result self.events.trigger('pre_execute') @@ -2685,10 +2685,10 @@ class InteractiveShell(SingletonConfigurable): # Compile to bytecode try: code_ast = compiler.ast_parse(cell, filename=cell_name) - except self.custom_exceptions as e: - etype, value, tb = sys.exc_info() - self.CustomTB(etype, value, tb) - return error_before_exec(e) + except self.custom_exceptions as e: + etype, value, tb = sys.exc_info() + self.CustomTB(etype, value, tb) + return error_before_exec(e) except IndentationError as e: self.showindentationerror() return error_before_exec(e) @@ -2710,10 +2710,10 @@ class InteractiveShell(SingletonConfigurable): # Execute the user code interactivity = "none" if silent else self.ast_node_interactivity - has_raised = self.run_ast_nodes(code_ast.body, cell_name, + has_raised = self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity, compiler=compiler, result=result) - - self.last_execution_succeeded = not has_raised + + self.last_execution_succeeded = not has_raised # Reset this so later displayed values do not modify the # ExecutionResult @@ -2731,16 +2731,16 @@ class InteractiveShell(SingletonConfigurable): self.execution_count += 1 return result - + def transform_ast(self, node): """Apply the AST transformations from self.ast_transformers - + Parameters ---------- node : ast.Node The root node to be transformed. Typically called with the ast.Module produced by parsing user input. - + Returns ------- An ast.Node corresponding to the node it was called with. Note that it @@ -2758,11 +2758,11 @@ class InteractiveShell(SingletonConfigurable): except Exception: warn("AST transformer %r threw an error. It will be unregistered." % transformer) self.ast_transformers.remove(transformer) - + if self.ast_transformers: ast.fix_missing_locations(node) return node - + def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', compiler=compile, result=None): @@ -2883,7 +2883,7 @@ class InteractiveShell(SingletonConfigurable): if result is not None: result.error_in_exec = e self.showtraceback(exception_only=True) - warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) + warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) except self.custom_exceptions: etype, value, tb = sys.exc_info() if result is not None: @@ -2928,17 +2928,17 @@ class InteractiveShell(SingletonConfigurable): def enable_gui(self, gui=None): raise NotImplementedError('Implement enable_gui in a subclass') - + def enable_matplotlib(self, gui=None): """Enable interactive matplotlib and inline figure support. - + This takes the following steps: - + 1. select the appropriate eventloop and matplotlib backend 2. set up matplotlib for interactive use with that backend 3. configure formatters for inline figure display 4. enable the selected gui eventloop - + Parameters ---------- gui : optional, string @@ -2952,7 +2952,7 @@ class InteractiveShell(SingletonConfigurable): """ from IPython.core import pylabtools as pt gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) - + if gui != 'inline': # If we have our first gui selection, store it if self.pylab_gui_select is None: @@ -2962,16 +2962,16 @@ class InteractiveShell(SingletonConfigurable): print ('Warning: Cannot change to a different GUI toolkit: %s.' ' Using %s instead.' % (gui, self.pylab_gui_select)) gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) - + pt.activate_matplotlib(backend) pt.configure_inline_support(self, backend) - + # Now we must activate the gui pylab wants to use, and fix %run to take # plot updates into account self.enable_gui(gui) self.magics_manager.registry['ExecutionMagics'].default_runner = \ pt.mpl_runner(self.safe_execfile) - + return gui, backend def enable_pylab(self, gui=None, import_all=True, welcome_message=False): @@ -2981,7 +2981,7 @@ class InteractiveShell(SingletonConfigurable): namespace all of numpy and pylab, and configures IPython to correctly interact with the GUI event loop. The GUI backend to be used can be optionally selected with the optional ``gui`` argument. - + This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. Parameters @@ -3001,9 +3001,9 @@ class InteractiveShell(SingletonConfigurable): This argument is ignored, no welcome message will be displayed. """ from IPython.core.pylabtools import import_pylab - + gui, backend = self.enable_matplotlib(gui) - + # We want to prevent the loading of pylab to pollute the user's # namespace as shown by the %who* magics, so we execute the activation # code in an empty namespace, and we update *both* user_ns and @@ -3076,19 +3076,19 @@ class InteractiveShell(SingletonConfigurable): tmp_file.close() return filename - @undoc + @undoc def write(self,data): - """DEPRECATED: Write a string to the default output""" - warn('InteractiveShell.write() is deprecated, use sys.stdout instead', - DeprecationWarning, stacklevel=2) - sys.stdout.write(data) + """DEPRECATED: Write a string to the default output""" + warn('InteractiveShell.write() is deprecated, use sys.stdout instead', + DeprecationWarning, stacklevel=2) + sys.stdout.write(data) - @undoc + @undoc def write_err(self,data): - """DEPRECATED: Write a string to the default error output""" - warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', - DeprecationWarning, stacklevel=2) - sys.stderr.write(data) + """DEPRECATED: Write a string to the default error output""" + warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', + DeprecationWarning, stacklevel=2) + sys.stderr.write(data) def ask_yes_no(self, prompt, default=None, interrupt=None): if self.quiet: @@ -3160,8 +3160,8 @@ class InteractiveShell(SingletonConfigurable): if code: return code try: - if target.startswith(('http://', 'https://')): - return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) + if target.startswith(('http://', 'https://')): + return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) except UnicodeDecodeError: if not py_only : # Deferred import @@ -3171,7 +3171,7 @@ class InteractiveShell(SingletonConfigurable): from urllib import urlopen response = urlopen(target) return response.read().decode('latin1') - raise ValueError(("'%s' seem to be unreadable.") % target) + raise ValueError(("'%s' seem to be unreadable.") % target) potential_target = [target] try : @@ -3253,11 +3253,11 @@ class InteractiveShell(SingletonConfigurable): self.restore_sys_module_state() - # Overridden in terminal subclass to change prompts - def switch_doctest_mode(self, mode): - pass - - + # Overridden in terminal subclass to change prompts + def switch_doctest_mode(self, mode): + pass + + class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): """An abstract base class for InteractiveShell.""" diff --git a/contrib/python/ipython/py2/IPython/core/magic.py b/contrib/python/ipython/py2/IPython/core/magic.py index 61a929fd23..f3a0b5be33 100644 --- a/contrib/python/ipython/py2/IPython/core/magic.py +++ b/contrib/python/ipython/py2/IPython/core/magic.py @@ -27,8 +27,8 @@ 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 +from traitlets import Bool, Dict, Instance, observe +from logging import error #----------------------------------------------------------------------------- # Globals @@ -298,12 +298,12 @@ class MagicsManager(Configurable): shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) - auto_magic = Bool(True, help= - "Automatically call line magics without requiring explicit % prefix" - ).tag(config=True) - @observe('auto_magic') - def _auto_magic_changed(self, change): - self.shell.automagic = change['new'] + auto_magic = Bool(True, help= + "Automatically call line magics without requiring explicit % prefix" + ).tag(config=True) + @observe('auto_magic') + def _auto_magic_changed(self, change): + self.shell.automagic = change['new'] _auto_status = [ 'Automagic is OFF, % prefix IS needed for line magics.', diff --git a/contrib/python/ipython/py2/IPython/core/magics/auto.py b/contrib/python/ipython/py2/IPython/core/magics/auto.py index f87bafdeb1..dc229d509b 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/auto.py +++ b/contrib/python/ipython/py2/IPython/core/magics/auto.py @@ -1,7 +1,7 @@ """Implementation of magic functions that control various automatic behaviors. """ from __future__ import print_function -from __future__ import absolute_import +from __future__ import absolute_import #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -17,7 +17,7 @@ from __future__ import absolute_import # Our own packages from IPython.core.magic import Bunch, Magics, magics_class, line_magic from IPython.testing.skipdoctest import skip_doctest -from logging import error +from logging import error #----------------------------------------------------------------------------- # Magic implementation classes diff --git a/contrib/python/ipython/py2/IPython/core/magics/basic.py b/contrib/python/ipython/py2/IPython/core/magics/basic.py index ca69e2e698..529cdd2b65 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/basic.py +++ b/contrib/python/ipython/py2/IPython/core/magics/basic.py @@ -1,7 +1,7 @@ """Implementation of basic magic functions.""" from __future__ import print_function -from __future__ import absolute_import +from __future__ import absolute_import import argparse import io @@ -15,8 +15,8 @@ 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 +from warnings import warn +from logging import error class MagicsDisplay(object): @@ -328,7 +328,7 @@ Currently the magic system has the following functions:""", """ def color_switch_err(name): warn('Error changing %s color schemes.\n%s' % - (name, sys.exc_info()[1]), stacklevel=2) + (name, sys.exc_info()[1]), stacklevel=2) new_scheme = parameter_s.strip() @@ -338,13 +338,13 @@ Currently the magic system has the following functions:""", # local shortcut shell = self.shell - # Set shell colour scheme + # Set shell colour scheme try: - shell.colors = new_scheme - shell.refresh_style() + shell.colors = new_scheme + shell.refresh_style() except: - color_switch_err('shell') - + color_switch_err('shell') + # Set exception colors try: shell.InteractiveTB.set_colors(scheme = new_scheme) @@ -458,12 +458,12 @@ Currently the magic system has the following functions:""", shell.magic('xmode ' + dstore.xmode) - # mode here is the state before we switch; switch_doctest_mode takes - # the mode we're switching to. - shell.switch_doctest_mode(not mode) - + # mode here is the state before we switch; switch_doctest_mode takes + # the mode we're switching to. + shell.switch_doctest_mode(not mode) + # Store new mode and inform - dstore.mode = bool(not mode) + dstore.mode = bool(not mode) mode_label = ['OFF','ON'][dstore.mode] print('Doctest mode is:', mode_label) diff --git a/contrib/python/ipython/py2/IPython/core/magics/code.py b/contrib/python/ipython/py2/IPython/core/magics/code.py index 4c1a40f197..c91d24c639 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/code.py +++ b/contrib/python/ipython/py2/IPython/core/magics/code.py @@ -1,7 +1,7 @@ """Implementation of code management magic functions. """ from __future__ import print_function -from __future__ import absolute_import +from __future__ import absolute_import #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -32,9 +32,9 @@ 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 -from logging import error +from IPython.utils.path import get_py_filename +from warnings import warn +from logging import error from IPython.utils.text import get_text_list #----------------------------------------------------------------------------- @@ -138,37 +138,37 @@ def extract_symbols(code, symbols): return blocks, not_found -def strip_initial_indent(lines): - """For %load, strip indent from lines until finding an unindented line. - - https://github.com/ipython/ipython/issues/9775 - """ - indent_re = re.compile(r'\s+') - - it = iter(lines) - first_line = next(it) - indent_match = indent_re.match(first_line) - - if indent_match: - # First line was indented - indent = indent_match.group() - yield first_line[len(indent):] - - for line in it: - if line.startswith(indent): - yield line[len(indent):] - else: - # Less indented than the first line - stop dedenting - yield line - break - else: - yield first_line - - # Pass the remaining lines through without dedenting - for line in it: - yield line - - +def strip_initial_indent(lines): + """For %load, strip indent from lines until finding an unindented line. + + https://github.com/ipython/ipython/issues/9775 + """ + indent_re = re.compile(r'\s+') + + it = iter(lines) + first_line = next(it) + indent_match = indent_re.match(first_line) + + if indent_match: + # First line was indented + indent = indent_match.group() + yield first_line[len(indent):] + + for line in it: + if line.startswith(indent): + yield line[len(indent):] + else: + # Less indented than the first line - stop dedenting + yield line + break + else: + yield first_line + + # Pass the remaining lines through without dedenting + for line in it: + yield line + + class InteractivelyDefined(Exception): """Exception for interactively defined variable in magic_edit""" def __init__(self, index): @@ -219,7 +219,7 @@ class CodeMagics(Magics): append = 'a' in opts mode = 'a' if append else 'w' ext = u'.ipy' if raw else u'.py' - fname, codefrom = args[0], " ".join(args[1:]) + fname, codefrom = args[0], " ".join(args[1:]) if not fname.endswith((u'.py',u'.ipy')): fname += ext file_exists = os.path.isfile(fname) @@ -371,7 +371,7 @@ class CodeMagics(Magics): lines = contents.split('\n') slices = extract_code_ranges(ranges) contents = [lines[slice(*slc)] for slc in slices] - contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents))) + contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents))) l = len(contents) diff --git a/contrib/python/ipython/py2/IPython/core/magics/config.py b/contrib/python/ipython/py2/IPython/core/magics/config.py index 9505697791..184388f064 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/config.py +++ b/contrib/python/ipython/py2/IPython/core/magics/config.py @@ -1,7 +1,7 @@ """Implementation of configuration-related magic functions. """ from __future__ import print_function -from __future__ import absolute_import +from __future__ import absolute_import #----------------------------------------------------------------------------- # Copyright (c) 2012 The IPython Development Team. # @@ -20,7 +20,7 @@ import re # Our own packages from IPython.core.error import UsageError from IPython.core.magic import Magics, magics_class, line_magic -from logging import error +from logging import error #----------------------------------------------------------------------------- # Magic implementation classes diff --git a/contrib/python/ipython/py2/IPython/core/magics/display.py b/contrib/python/ipython/py2/IPython/core/magics/display.py index c4a8f44d9a..a0a74a62cc 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/display.py +++ b/contrib/python/ipython/py2/IPython/core/magics/display.py @@ -25,32 +25,32 @@ from IPython.core.magic import ( @magics_class class DisplayMagics(Magics): """Magics for displaying various output types with literals - - Defines javascript/latex/svg/html cell magics for writing + + Defines javascript/latex/svg/html cell magics for writing blocks in those languages, to be rendered in the frontend. """ - - @cell_magic - def js(self, line, cell): - """Run the cell block of Javascript code - - Alias of `%%javascript` - """ - self.javascript(line, cell) - + @cell_magic + def js(self, line, cell): + """Run the cell block of Javascript code + + Alias of `%%javascript` + """ + self.javascript(line, cell) + + @cell_magic def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell)) - - + + @cell_magic def latex(self, line, cell): """Render the cell as a block of latex - + The subset of latex which is support depends on the implementation in - the client. In the Jupyter Notebook, this magic only renders the subset - of latex defined by MathJax + the client. In the Jupyter Notebook, this magic only renders the subset + of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell)) diff --git a/contrib/python/ipython/py2/IPython/core/magics/execution.py b/contrib/python/ipython/py2/IPython/core/magics/execution.py index 3734b0cdae..2597cab3fc 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/execution.py +++ b/contrib/python/ipython/py2/IPython/core/magics/execution.py @@ -5,7 +5,7 @@ # Distributed under the terms of the Modified BSD License. from __future__ import print_function -from __future__ import absolute_import +from __future__ import absolute_import import ast import bdb @@ -28,7 +28,7 @@ except ImportError: except ImportError: profile = pstats = None -from IPython.core import oinspect +from IPython.core import oinspect from IPython.core import magic_arguments from IPython.core import page from IPython.core.error import UsageError @@ -42,10 +42,10 @@ from IPython.utils.contexts import preserve_keys from IPython.utils.capture import capture_output from IPython.utils.ipstruct import Struct from IPython.utils.module_paths import find_mod -from IPython.utils.path import get_py_filename, shellglob +from IPython.utils.path import get_py_filename, shellglob from IPython.utils.timing import clock, clock2 -from warnings import warn -from logging import error +from warnings import warn +from logging import error if PY3: from io import StringIO @@ -61,12 +61,12 @@ class TimeitResult(object): """ Object returned by the timeit magic with info about the run. - Contains the following attributes : + Contains the following attributes : - loops: (int) number of loops done per measurement - repeat: (int) number of times the measurement has been repeated - best: (float) best execution time / number - all_runs: (list of float) execution time of each run (in s) + loops: (int) number of loops done per measurement + repeat: (int) number of times the measurement has been repeated + best: (float) best execution time / number + all_runs: (list of float) execution time of each run (in s) compile_time: (float) time of statement compilation (s) """ @@ -705,54 +705,54 @@ python-profiler package from non-free.""") try: stats = None - if 'p' in opts: - stats = self._run_with_profiler(code, opts, code_ns) - else: - if 'd' in opts: - bp_file, bp_line = parse_breakpoint( - opts.get('b', ['1'])[0], filename) - self._run_with_debugger( - code, code_ns, filename, bp_line, bp_file) + if 'p' in opts: + stats = self._run_with_profiler(code, opts, code_ns) + else: + if 'd' in opts: + bp_file, bp_line = parse_breakpoint( + opts.get('b', ['1'])[0], filename) + self._run_with_debugger( + code, code_ns, filename, bp_line, bp_file) else: - if 'm' in opts: - def run(): - self.shell.safe_run_module(modulename, prog_ns) + if 'm' in opts: + def run(): + self.shell.safe_run_module(modulename, prog_ns) else: - if runner is None: - runner = self.default_runner - if runner is None: - runner = self.shell.safe_execfile - - def run(): - runner(filename, prog_ns, prog_ns, - exit_ignore=exit_ignore) - - if 't' in opts: - # timed execution - try: - nruns = int(opts['N'][0]) - if nruns < 1: - error('Number of runs must be >=1') - return - except (KeyError): - nruns = 1 - self._run_with_timing(run, nruns) - else: - # regular execution - run() - - if 'i' in opts: - self.shell.user_ns['__name__'] = __name__save - else: - # update IPython interactive namespace - - # Some forms of read errors on the file may mean the - # __name__ key was never set; using pop we don't have to - # worry about a possible KeyError. - prog_ns.pop('__name__', None) - - with preserve_keys(self.shell.user_ns, '__file__'): - self.shell.user_ns.update(prog_ns) + if runner is None: + runner = self.default_runner + if runner is None: + runner = self.shell.safe_execfile + + def run(): + runner(filename, prog_ns, prog_ns, + exit_ignore=exit_ignore) + + if 't' in opts: + # timed execution + try: + nruns = int(opts['N'][0]) + if nruns < 1: + error('Number of runs must be >=1') + return + except (KeyError): + nruns = 1 + self._run_with_timing(run, nruns) + else: + # regular execution + run() + + if 'i' in opts: + self.shell.user_ns['__name__'] = __name__save + else: + # update IPython interactive namespace + + # Some forms of read errors on the file may mean the + # __name__ key was never set; using pop we don't have to + # worry about a possible KeyError. + prog_ns.pop('__name__', None) + + with preserve_keys(self.shell.user_ns, '__file__'): + self.shell.user_ns.update(prog_ns) finally: # It's a bit of a mystery why, but __builtins__ can change from # being a module to becoming a dict missing some key data after @@ -801,11 +801,11 @@ python-profiler package from non-free.""") If the break point given by `bp_line` is not valid. """ - deb = self.shell.InteractiveTB.pdb - if not deb: - self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() - deb = self.shell.InteractiveTB.pdb - + deb = self.shell.InteractiveTB.pdb + if not deb: + self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() + deb = self.shell.InteractiveTB.pdb + # deb.checkline() fails if deb.curframe exists but is None; it can # handle it not existing. https://github.com/ipython/ipython/issues/10028 if hasattr(deb, 'curframe'): diff --git a/contrib/python/ipython/py2/IPython/core/magics/history.py b/contrib/python/ipython/py2/IPython/core/magics/history.py index 5967591394..d24bfd2a4e 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/history.py +++ b/contrib/python/ipython/py2/IPython/core/magics/history.py @@ -15,7 +15,7 @@ from __future__ import print_function # Stdlib import os -import sys +import sys from io import open as io_open # Our own packages @@ -148,7 +148,7 @@ class HistoryMagics(Magics): # Check if output to specific file was requested. outfname = args.filename if not outfname: - outfile = sys.stdout # default + outfile = sys.stdout # default # We don't want to close stdout at the end! close_at_end = False else: diff --git a/contrib/python/ipython/py2/IPython/core/magics/logging.py b/contrib/python/ipython/py2/IPython/core/magics/logging.py index 90214ab54a..22500f8156 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/logging.py +++ b/contrib/python/ipython/py2/IPython/core/magics/logging.py @@ -18,7 +18,7 @@ import sys # Our own packages from IPython.core.magic import Magics, magics_class, line_magic -from warnings import warn +from warnings import warn from IPython.utils.py3compat import str_to_unicode #----------------------------------------------------------------------------- diff --git a/contrib/python/ipython/py2/IPython/core/magics/osm.py b/contrib/python/ipython/py2/IPython/core/magics/osm.py index 352cf2d451..f48259ee02 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/osm.py +++ b/contrib/python/ipython/py2/IPython/core/magics/osm.py @@ -323,7 +323,7 @@ class OSMagics(Magics): else: - opts, ps = self.parse_options(parameter_s, 'qb', mode='string') + opts, ps = self.parse_options(parameter_s, 'qb', mode='string') # jump to previous if ps == '-': try: @@ -437,7 +437,7 @@ class OSMagics(Magics): """ dir_s = self.shell.dir_stack - tgt = os.path.expanduser(parameter_s) + tgt = os.path.expanduser(parameter_s) cwd = py3compat.getcwd().replace(self.shell.home_dir,'~') if tgt: self.cd(parameter_s) @@ -775,8 +775,8 @@ class OSMagics(Magics): The file will be overwritten unless the -a (--append) flag is specified. """ args = magic_arguments.parse_argstring(self.writefile, line) - filename = os.path.expanduser(args.filename) - + filename = os.path.expanduser(args.filename) + if os.path.exists(filename): if args.append: print("Appending to %s" % filename) diff --git a/contrib/python/ipython/py2/IPython/core/magics/pylab.py b/contrib/python/ipython/py2/IPython/core/magics/pylab.py index 6c5cd68a59..62308d5e49 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/pylab.py +++ b/contrib/python/ipython/py2/IPython/core/magics/pylab.py @@ -18,7 +18,7 @@ from traitlets.config.application import Application from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic from IPython.testing.skipdoctest import skip_doctest -from warnings import warn +from warnings import warn from IPython.core.pylabtools import backends #----------------------------------------------------------------------------- diff --git a/contrib/python/ipython/py2/IPython/core/magics/script.py b/contrib/python/ipython/py2/IPython/core/magics/script.py index 3fbddc38a8..bfcad64919 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/script.py +++ b/contrib/python/ipython/py2/IPython/core/magics/script.py @@ -1,8 +1,8 @@ """Magic functions for running cells in various scripts.""" from __future__ import print_function -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. import errno import os @@ -19,7 +19,7 @@ from IPython.core.magic import ( from IPython.lib.backgroundjobs import BackgroundJobManager from IPython.utils import py3compat from IPython.utils.process import arg_split -from traitlets import List, Dict, default +from traitlets import List, Dict, default #----------------------------------------------------------------------------- # Magic implementation classes @@ -68,7 +68,7 @@ class ScriptMagics(Magics): with a program in a subprocess, and registers a few top-level magics that call %%script with common interpreters. """ - script_magics = List( + script_magics = List( help="""Extra script cell magics to define This generates simple wrappers of `%%script foo` as `%%foo`. @@ -76,8 +76,8 @@ class ScriptMagics(Magics): If you want to add script magics that aren't on your path, specify them in script_paths """, - ).tag(config=True) - @default('script_magics') + ).tag(config=True) + @default('script_magics') def _script_magics_default(self): """default to a common list of programs""" @@ -98,13 +98,13 @@ class ScriptMagics(Magics): return defaults - script_paths = Dict( + script_paths = Dict( help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby' Only necessary for items in script_magics where the default path will not find the right interpreter. """ - ).tag(config=True) + ).tag(config=True) def __init__(self, shell=None): super(ScriptMagics, self).__init__(shell=shell) diff --git a/contrib/python/ipython/py2/IPython/core/oinspect.py b/contrib/python/ipython/py2/IPython/core/oinspect.py index 55a4efe8c0..b11e24e435 100644 --- a/contrib/python/ipython/py2/IPython/core/oinspect.py +++ b/contrib/python/ipython/py2/IPython/core/oinspect.py @@ -17,7 +17,7 @@ __all__ = ['Inspector','InspectColors'] # stdlib modules import inspect import linecache -import warnings +import warnings import os from textwrap import dedent import types @@ -42,19 +42,19 @@ 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.signatures import signature -from IPython.utils.colorable import Colorable +from IPython.utils.colorable import Colorable -from pygments import highlight +from pygments import highlight try: # PythonLexer was renamed to Python2Lexer in pygments 2.5 from pygments.lexers import Python2Lexer except ImportError: from pygments.lexers import PythonLexer as Python2Lexer -from pygments.formatters import HtmlFormatter - -def pylight(code): +from pygments.formatters import HtmlFormatter + +def pylight(code): return highlight(code, Python2Lexer(), HtmlFormatter(noclasses=True)) - + # builtin docstrings to ignore _func_call_docstring = types.FunctionType.__call__.__doc__ _object_init_docstring = object.__init__.__doc__ @@ -124,8 +124,8 @@ def getdoc(obj): It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms - (like Pyro proxies) to still be inspected by ipython's ? system. - """ + (like Pyro proxies) to still be inspected by ipython's ? system. + """ # Allow objects to offer customized documentation via a getdoc method: try: ds = obj.getdoc() @@ -141,7 +141,7 @@ def getdoc(obj): return py3compat.cast_unicode(docstr, encoding=encoding) except Exception: # Harden against an inspect failure, which can occur with - # extensions modules. + # extensions modules. raise return None @@ -376,16 +376,16 @@ def find_source_lines(obj): return lineno -class Inspector(Colorable): +class Inspector(Colorable): def __init__(self, color_table=InspectColors, code_color_table=PyColorize.ANSICodeColors, scheme='NoColor', - str_detail_level=0, - parent=None, config=None): - super(Inspector, self).__init__(parent=parent, config=config) + str_detail_level=0, + parent=None, config=None): + super(Inspector, self).__init__(parent=parent, config=config) self.color_table = color_table - self.parser = PyColorize.Parser(out='str', parent=self, style=scheme) + self.parser = PyColorize.Parser(out='str', parent=self, style=scheme) self.format = self.parser.format self.str_detail_level = str_detail_level self.set_active_scheme(scheme) @@ -438,11 +438,11 @@ class Inspector(Colorable): if output is None: self.noinfo('definition header',oname) else: - print(header,self.format(output), end=' ') + print(header,self.format(output), end=' ') # In Python 3, all classes are new-style, so they all have __init__. @skip_doctest_py3 - def pdoc(self, obj, oname='', formatter=None): + def pdoc(self, obj, oname='', formatter=None): """Print the docstring for any object. Optional: @@ -480,7 +480,7 @@ class Inspector(Colorable): lines = [] ds = getdoc(obj) if formatter: - ds = formatter(ds).get('plain/text', ds) + ds = formatter(ds).get('plain/text', ds) if ds: lines.append(head("Class docstring:")) lines.append(indent(ds)) @@ -517,7 +517,7 @@ class Inspector(Colorable): def pfile(self, obj, oname=''): """Show the whole file where an object was defined.""" - + lineno = find_source_lines(obj) if lineno is None: self.noinfo('file', oname) @@ -553,184 +553,184 @@ class Inspector(Colorable): title_width = max(len(title) + 2 for title, _ in fields) for title, content in fields: if len(content.splitlines()) > 1: - title = header(title + ':') + '\n' + title = header(title + ':') + '\n' else: - title = header((title + ':').ljust(title_width)) + title = header((title + ':').ljust(title_width)) out.append(cast_unicode(title) + cast_unicode(content)) return "\n".join(out) - def _mime_format(self, text, formatter=None): - """Return a mime bundle representation of the input text. - - - if `formatter` is None, the returned mime bundle has - a `text/plain` field, with the input text. - a `text/html` field with a `<pre>` tag containing the input text. - - - if `formatter` is not None, it must be a callable transforming the - input text into a mime bundle. Default values for `text/plain` and - `text/html` representations are the ones described above. - - Note: - - Formatters returning strings are supported but this behavior is deprecated. - - """ - text = cast_unicode(text) - defaults = { - 'text/plain': text, - 'text/html': '<pre>' + text + '</pre>' - } - - if formatter is None: - return defaults - else: - formatted = formatter(text) - - if not isinstance(formatted, dict): - # Handle the deprecated behavior of a formatter returning - # a string instead of a mime bundle. - return { - 'text/plain': formatted, - 'text/html': '<pre>' + formatted + '</pre>' - } - - else: - return dict(defaults, **formatted) - - - def format_mime(self, bundle): - - text_plain = bundle['text/plain'] - - text = '' - heads, bodies = list(zip(*text_plain)) - _len = max(len(h) for h in heads) - - for head, body in zip(heads, bodies): - body = body.strip('\n') - delim = '\n' if '\n' in body else ' ' - text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n' - - bundle['text/plain'] = text - return bundle - - def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0): - """Retrieve an info dict and format it.""" - - info = self._info(obj, oname=oname, info=info, detail_level=detail_level) - - _mime = { - 'text/plain': [], - 'text/html': '', - } - - def append_field(bundle, title, key, formatter=None): - field = info[key] - if field is not None: - formatted_field = self._mime_format(field, formatter) - bundle['text/plain'].append((title, formatted_field['text/plain'])) - bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n' - - def code_formatter(text): - return { - 'text/plain': self.format(text), - 'text/html': pylight(text) - } - + def _mime_format(self, text, formatter=None): + """Return a mime bundle representation of the input text. + + - if `formatter` is None, the returned mime bundle has + a `text/plain` field, with the input text. + a `text/html` field with a `<pre>` tag containing the input text. + + - if `formatter` is not None, it must be a callable transforming the + input text into a mime bundle. Default values for `text/plain` and + `text/html` representations are the ones described above. + + Note: + + Formatters returning strings are supported but this behavior is deprecated. + + """ + text = cast_unicode(text) + defaults = { + 'text/plain': text, + 'text/html': '<pre>' + text + '</pre>' + } + + if formatter is None: + return defaults + else: + formatted = formatter(text) + + if not isinstance(formatted, dict): + # Handle the deprecated behavior of a formatter returning + # a string instead of a mime bundle. + return { + 'text/plain': formatted, + 'text/html': '<pre>' + formatted + '</pre>' + } + + else: + return dict(defaults, **formatted) + + + def format_mime(self, bundle): + + text_plain = bundle['text/plain'] + + text = '' + heads, bodies = list(zip(*text_plain)) + _len = max(len(h) for h in heads) + + for head, body in zip(heads, bodies): + body = body.strip('\n') + delim = '\n' if '\n' in body else ' ' + text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n' + + bundle['text/plain'] = text + return bundle + + def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0): + """Retrieve an info dict and format it.""" + + info = self._info(obj, oname=oname, info=info, detail_level=detail_level) + + _mime = { + 'text/plain': [], + 'text/html': '', + } + + def append_field(bundle, title, key, formatter=None): + field = info[key] + if field is not None: + formatted_field = self._mime_format(field, formatter) + bundle['text/plain'].append((title, formatted_field['text/plain'])) + bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n' + + def code_formatter(text): + return { + 'text/plain': self.format(text), + 'text/html': pylight(text) + } + if info['isalias']: - append_field(_mime, 'Repr', 'string_form') + append_field(_mime, 'Repr', 'string_form') elif info['ismagic']: - if detail_level > 0: - append_field(_mime, 'Source', 'source', code_formatter) + if detail_level > 0: + append_field(_mime, 'Source', 'source', code_formatter) else: - append_field(_mime, 'Docstring', 'docstring', formatter) - append_field(_mime, 'File', 'file') + append_field(_mime, 'Docstring', 'docstring', formatter) + append_field(_mime, 'File', 'file') elif info['isclass'] or is_simple_callable(obj): # Functions, methods, classes - append_field(_mime, 'Signature', 'definition', code_formatter) - append_field(_mime, 'Init signature', 'init_definition', code_formatter) + append_field(_mime, 'Signature', 'definition', code_formatter) + append_field(_mime, 'Init signature', 'init_definition', code_formatter) if detail_level > 0 and info['source']: - append_field(_mime, 'Source', 'source', code_formatter) + append_field(_mime, 'Source', 'source', code_formatter) else: - append_field(_mime, 'Docstring', 'docstring', formatter) - append_field(_mime, 'Init docstring', 'init_docstring', formatter) + append_field(_mime, 'Docstring', 'docstring', formatter) + append_field(_mime, 'Init docstring', 'init_docstring', formatter) - append_field(_mime, 'File', 'file') - append_field(_mime, 'Type', 'type_name') + append_field(_mime, 'File', 'file') + append_field(_mime, 'Type', 'type_name') else: # General Python objects append_field(_mime, 'Signature', 'definition', code_formatter) append_field(_mime, 'Call signature', 'call_def', code_formatter) - append_field(_mime, 'Type', 'type_name') + append_field(_mime, 'Type', 'type_name') # Base class for old-style instances if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']: - append_field(_mime, 'Base Class', 'base_class') + append_field(_mime, 'Base Class', 'base_class') - append_field(_mime, 'String form', 'string_form') + append_field(_mime, 'String form', 'string_form') # Namespace if info['namespace'] != 'Interactive': - append_field(_mime, 'Namespace', 'namespace') + append_field(_mime, 'Namespace', 'namespace') - append_field(_mime, 'Length', 'length') + append_field(_mime, 'Length', 'length') append_field(_mime, 'File', 'file') # Source or docstring, depending on detail level and whether # source found. - if detail_level > 0: - append_field(_mime, 'Source', 'source', code_formatter) - else: - append_field(_mime, 'Docstring', 'docstring', formatter) - - append_field(_mime, 'Class docstring', 'class_docstring', formatter) - append_field(_mime, 'Init docstring', 'init_docstring', formatter) - append_field(_mime, 'Call docstring', 'call_docstring', formatter) + if detail_level > 0: + append_field(_mime, 'Source', 'source', code_formatter) + else: + append_field(_mime, 'Docstring', 'docstring', formatter) + + append_field(_mime, 'Class docstring', 'class_docstring', formatter) + append_field(_mime, 'Init docstring', 'init_docstring', formatter) + append_field(_mime, 'Call docstring', 'call_docstring', formatter) - - return self.format_mime(_mime) - - def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True): + + return self.format_mime(_mime) + + def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True): """Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - - formatter: callable (optional) - A special formatter for docstrings. - - The formatter is a callable that takes a string as an input - and returns either a formatted string or a mime type bundle - in the form of a dictionnary. - - Although the support of custom formatter returning a string - instead of a mime type bundle is deprecated. + - formatter: callable (optional) + A special formatter for docstrings. + The formatter is a callable that takes a string as an input + and returns either a formatted string or a mime type bundle + in the form of a dictionnary. + + Although the support of custom formatter returning a string + instead of a mime type bundle is deprecated. + - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given. """ - info = self._get_info(obj, oname, formatter, info, detail_level) - if not enable_html_pager: - del info['text/html'] - page.page(info) - + info = self._get_info(obj, oname, formatter, info, detail_level) + if not enable_html_pager: + del info['text/html'] + page.page(info) + def info(self, obj, oname='', formatter=None, info=None, detail_level=0): - """DEPRECATED. Compute a dict with detailed information about an object. - """ - if formatter is not None: - warnings.warn('The `formatter` keyword argument to `Inspector.info`' - 'is deprecated as of IPython 5.0 and will have no effects.', - DeprecationWarning, stacklevel=2) - return self._info(obj, oname=oname, info=info, detail_level=detail_level) - - def _info(self, obj, oname='', info=None, detail_level=0): + """DEPRECATED. Compute a dict with detailed information about an object. + """ + if formatter is not None: + warnings.warn('The `formatter` keyword argument to `Inspector.info`' + 'is deprecated as of IPython 5.0 and will have no effects.', + DeprecationWarning, stacklevel=2) + return self._info(obj, oname=oname, info=info, detail_level=detail_level) + + def _info(self, obj, oname='', info=None, detail_level=0): """Compute a dict with detailed information about an object. Optional arguments: @@ -774,7 +774,7 @@ class Inspector(Colorable): out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) string_max = 200 # max size of strings to show (snipped if longer) - shalf = int((string_max - 5) / 2) + shalf = int((string_max - 5) / 2) if ismagic: obj_type_name = 'Magic function' @@ -846,43 +846,43 @@ class Inspector(Colorable): # Constructor docstring for classes if inspect.isclass(obj): out['isclass'] = True - - # get the init signature: + + # get the init signature: try: - init_def = self._getdef(obj, oname) + init_def = self._getdef(obj, oname) except AttributeError: - init_def = None - - # get the __init__ docstring - try: - obj_init = obj.__init__ - except AttributeError: - init_ds = None + init_def = None + + # get the __init__ docstring + try: + obj_init = obj.__init__ + except AttributeError: + init_ds = None else: - if init_def is None: - # Get signature from init if top-level sig failed. - # Can happen for built-in types (list, etc.). - try: - init_def = self._getdef(obj_init, oname) - except AttributeError: - pass - init_ds = getdoc(obj_init) + if init_def is None: + # Get signature from init if top-level sig failed. + # Can happen for built-in types (list, etc.). + try: + init_def = self._getdef(obj_init, oname) + except AttributeError: + pass + init_ds = getdoc(obj_init) # Skip Python's auto-generated docstrings if init_ds == _object_init_docstring: init_ds = None - if init_def: - out['init_definition'] = init_def - - if init_ds: - out['init_docstring'] = init_ds + if init_def: + out['init_definition'] = init_def + if init_ds: + out['init_docstring'] = init_ds + # and class docstring for instances: else: # reconstruct the function definition and print it: defln = self._getdef(obj, oname) if defln: - out['definition'] = defln + out['definition'] = defln # First, check whether the instance docstring is identical to the # class one, and print it separately if they don't coincide. In @@ -915,10 +915,10 @@ class Inspector(Colorable): # Call form docstring for callable instances if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): call_def = self._getdef(obj.__call__, oname) - if call_def and (call_def != out.get('definition')): + if call_def and (call_def != out.get('definition')): # it may never be the case that call def and definition differ, # but don't include the same signature twice - out['call_def'] = call_def + out['call_def'] = call_def call_ds = getdoc(obj.__call__) # Skip Python's auto-generated docstrings if call_ds == _func_call_docstring: diff --git a/contrib/python/ipython/py2/IPython/core/page.py b/contrib/python/ipython/py2/IPython/core/page.py index 6d213c9f29..a9de4f4805 100644 --- a/contrib/python/ipython/py2/IPython/core/page.py +++ b/contrib/python/ipython/py2/IPython/core/page.py @@ -38,7 +38,7 @@ def display_page(strng, start=0, screen_lines=25): else: if start: strng = u'\n'.join(strng.splitlines()[start:]) - data = { 'text/plain': strng } + data = { 'text/plain': strng } display(data, raw=True) @@ -56,25 +56,25 @@ def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works. Only moves forward, same interface as page(), except for pager_cmd and - mode. - """ - if isinstance(strng, dict): - strng = strng.get('text/plain', '') + mode. + """ + if isinstance(strng, dict): + strng = strng.get('text/plain', '') out_ln = strng.splitlines()[start:] screens = chop(out_ln,screen_lines-1) if len(screens) == 1: - print(os.linesep.join(screens[0])) + print(os.linesep.join(screens[0])) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) - print(last_escape + hunk) + print(last_escape + hunk) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] - print(last_escape + os.linesep.join(screens[-1])) + print(last_escape + os.linesep.join(screens[-1])) def _detect_screen_size(screen_lines_def): """Attempt to work out the number of lines on the screen. @@ -192,13 +192,13 @@ def pager_page(strng, start=0, screen_lines=0, pager_cmd=None): try: screen_lines += _detect_screen_size(screen_lines_def) except (TypeError, UnsupportedOperation): - print(str_toprint) + print(str_toprint) return #print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines : #print '*** normal print' # dbg - print(str_toprint) + print(str_toprint) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return @@ -300,7 +300,7 @@ def get_pager_cmd(pager_cmd=None): Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': - default_pager_cmd = 'less -R' # -R for color control sequences + default_pager_cmd = 'less -R' # -R for color control sequences elif os.name in ['nt','dos']: default_pager_cmd = 'type' @@ -309,10 +309,10 @@ def get_pager_cmd(pager_cmd=None): pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd - - if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower(): - pager_cmd += ' -R' - + + if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower(): + pager_cmd += ' -R' + return pager_cmd @@ -340,13 +340,13 @@ if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': @return: True if need print more lines, False if quit """ - sys.stdout.write('---Return to continue, q to quit--- ') + sys.stdout.write('---Return to continue, q to quit--- ') ans = msvcrt.getwch() if ans in ("q", "Q"): result = False else: result = True - sys.stdout.write("\b"*37 + " "*37 + "\b"*37) + sys.stdout.write("\b"*37 + " "*37 + "\b"*37) return result else: def page_more(): diff --git a/contrib/python/ipython/py2/IPython/core/prefilter.py b/contrib/python/ipython/py2/IPython/core/prefilter.py index cbed3fd80a..1f2367fe52 100644 --- a/contrib/python/ipython/py2/IPython/core/prefilter.py +++ b/contrib/python/ipython/py2/IPython/core/prefilter.py @@ -6,8 +6,8 @@ Prefilters transform user input before it is exec'd by Python. These transforms are used to implement additional syntax such as !ls and %magic. """ -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. from keyword import iskeyword import re @@ -24,7 +24,7 @@ from IPython.core.macro import Macro from IPython.core.splitinput import LineInfo from traitlets import ( - List, Integer, Unicode, Bool, Instance, CRegExp + List, Integer, Unicode, Bool, Instance, CRegExp ) #----------------------------------------------------------------------------- @@ -114,7 +114,7 @@ class PrefilterManager(Configurable): or :meth:`sort_transformers` method after changing the priority. """ - multi_line_specials = Bool(True).tag(config=True) + multi_line_specials = Bool(True).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) def __init__(self, shell=None, **kwargs): @@ -344,12 +344,12 @@ class PrefilterManager(Configurable): class PrefilterTransformer(Configurable): """Transform a line of user input.""" - priority = Integer(100).tag(config=True) + priority = Integer(100).tag(config=True) # Transformers don't currently use shell or prefilter_manager, but as we # move away from checkers and handlers, they will need them. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) - enabled = Bool(True).tag(config=True) + enabled = Bool(True).tag(config=True) def __init__(self, shell=None, prefilter_manager=None, **kwargs): super(PrefilterTransformer, self).__init__( @@ -374,10 +374,10 @@ class PrefilterTransformer(Configurable): class PrefilterChecker(Configurable): """Inspect an input line and return a handler for that line.""" - priority = Integer(100).tag(config=True) + priority = Integer(100).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) - enabled = Bool(True).tag(config=True) + enabled = Bool(True).tag(config=True) def __init__(self, shell=None, prefilter_manager=None, **kwargs): super(PrefilterChecker, self).__init__( @@ -396,8 +396,8 @@ class PrefilterChecker(Configurable): class EmacsChecker(PrefilterChecker): - priority = Integer(100).tag(config=True) - enabled = Bool(False).tag(config=True) + priority = Integer(100).tag(config=True) + enabled = Bool(False).tag(config=True) def check(self, line_info): "Emacs ipython-mode tags certain input lines." @@ -409,7 +409,7 @@ class EmacsChecker(PrefilterChecker): class MacroChecker(PrefilterChecker): - priority = Integer(250).tag(config=True) + priority = Integer(250).tag(config=True) def check(self, line_info): obj = self.shell.user_ns.get(line_info.ifun) @@ -421,7 +421,7 @@ class MacroChecker(PrefilterChecker): class IPyAutocallChecker(PrefilterChecker): - priority = Integer(300).tag(config=True) + priority = Integer(300).tag(config=True) def check(self, line_info): "Instances of IPyAutocall in user_ns get autocalled immediately" @@ -435,7 +435,7 @@ class IPyAutocallChecker(PrefilterChecker): class AssignmentChecker(PrefilterChecker): - priority = Integer(600).tag(config=True) + priority = Integer(600).tag(config=True) def check(self, line_info): """Check to see if user is assigning to a var for the first time, in @@ -453,7 +453,7 @@ class AssignmentChecker(PrefilterChecker): class AutoMagicChecker(PrefilterChecker): - priority = Integer(700).tag(config=True) + priority = Integer(700).tag(config=True) def check(self, line_info): """If the ifun is magic, and automagic is on, run it. Note: normal, @@ -477,7 +477,7 @@ class AutoMagicChecker(PrefilterChecker): class PythonOpsChecker(PrefilterChecker): - priority = Integer(900).tag(config=True) + priority = Integer(900).tag(config=True) def check(self, line_info): """If the 'rest' of the line begins with a function call or pretty much @@ -492,14 +492,14 @@ class PythonOpsChecker(PrefilterChecker): class AutocallChecker(PrefilterChecker): - priority = Integer(1000).tag(config=True) + priority = Integer(1000).tag(config=True) - function_name_regexp = CRegExp(re_fun_name, - help="RegExp to identify potential function names." - ).tag(config=True) - exclude_regexp = CRegExp(re_exclude_auto, - help="RegExp to exclude strings with this start from autocalling." - ).tag(config=True) + function_name_regexp = CRegExp(re_fun_name, + help="RegExp to identify potential function names." + ).tag(config=True) + exclude_regexp = CRegExp(re_exclude_auto, + help="RegExp to exclude strings with this start from autocalling." + ).tag(config=True) def check(self, line_info): "Check if the initial word/function is callable and autocall is on." diff --git a/contrib/python/ipython/py2/IPython/core/profileapp.py b/contrib/python/ipython/py2/IPython/core/profileapp.py index b8e5fd26ac..3f9ce97b8b 100644 --- a/contrib/python/ipython/py2/IPython/core/profileapp.py +++ b/contrib/python/ipython/py2/IPython/core/profileapp.py @@ -32,7 +32,7 @@ from IPython.core.profiledir import ProfileDir from IPython.utils.importstring import import_item from IPython.paths import get_ipython_dir, get_ipython_package_dir from IPython.utils import py3compat -from traitlets import Unicode, Bool, Dict, observe +from traitlets import Unicode, Bool, Dict, observe #----------------------------------------------------------------------------- # Constants @@ -149,14 +149,14 @@ class ProfileList(Application): ) )) - ipython_dir = Unicode(get_ipython_dir(), + ipython_dir = Unicode(get_ipython_dir(), help=""" The name of the IPython directory. This directory is used for logging configuration (through profiles), history storage, etc. The default is usually $HOME/.ipython. This options can also be specified through the environment variable IPYTHONDIR. """ - ).tag(config=True) + ).tag(config=True) def _print_profiles(self, profiles): @@ -211,24 +211,24 @@ class ProfileCreate(BaseIPythonApplication): name = u'ipython-profile' description = create_help examples = _create_examples - auto_create = Bool(True) + auto_create = Bool(True) def _log_format_default(self): return "[%(name)s] %(message)s" def _copy_config_files_default(self): return True - parallel = Bool(False, - help="whether to include parallel computing config files" - ).tag(config=True) - - @observe('parallel') - def _parallel_changed(self, change): + parallel = Bool(False, + help="whether to include parallel computing config files" + ).tag(config=True) + + @observe('parallel') + def _parallel_changed(self, change): parallel_files = [ 'ipcontroller_config.py', 'ipengine_config.py', 'ipcluster_config.py' ] - if change['new']: + if change['new']: for cf in parallel_files: self.config_files.append(cf) else: diff --git a/contrib/python/ipython/py2/IPython/core/profiledir.py b/contrib/python/ipython/py2/IPython/core/profiledir.py index b777f13da0..e0e754a78f 100644 --- a/contrib/python/ipython/py2/IPython/core/profiledir.py +++ b/contrib/python/ipython/py2/IPython/core/profiledir.py @@ -12,7 +12,7 @@ from traitlets.config.configurable import LoggingConfigurable from IPython.paths import get_ipython_package_dir from IPython.utils.path import expand_path, ensure_dir_exists from IPython.utils import py3compat -from traitlets import Unicode, Bool, observe +from traitlets import Unicode, Bool, observe #----------------------------------------------------------------------------- # Module errors @@ -47,18 +47,18 @@ class ProfileDir(LoggingConfigurable): pid_dir = Unicode(u'') static_dir = Unicode(u'') - location = Unicode(u'', + location = Unicode(u'', help="""Set the profile location directly. This overrides the logic used by the `profile` option.""", - ).tag(config=True) + ).tag(config=True) _location_isset = Bool(False) # flag for detecting multiply set location - @observe('location') - def _location_changed(self, change): + @observe('location') + def _location_changed(self, change): if self._location_isset: raise RuntimeError("Cannot set profile location more than once.") self._location_isset = True - new = change['new'] + new = change['new'] ensure_dir_exists(new) # ensure config files exist: @@ -68,7 +68,7 @@ class ProfileDir(LoggingConfigurable): self.pid_dir = os.path.join(new, self.pid_dir_name) self.static_dir = os.path.join(new, self.static_dir_name) self.check_dirs() - + def _mkdir(self, path, mode=None): """ensure a directory exists at a given path @@ -102,13 +102,13 @@ class ProfileDir(LoggingConfigurable): raise return True - - @observe('log_dir') - def check_log_dir(self, change=None): + + @observe('log_dir') + def check_log_dir(self, change=None): self._mkdir(self.log_dir) - - @observe('startup_dir') - def check_startup_dir(self, change=None): + + @observe('startup_dir') + def check_startup_dir(self, change=None): self._mkdir(self.startup_dir) readme = os.path.join(self.startup_dir, 'README') @@ -118,12 +118,12 @@ class ProfileDir(LoggingConfigurable): with open(readme, 'wb') as f: f.write(pkgutil.get_data(__name__, 'profile/README_STARTUP')) - @observe('security_dir') - def check_security_dir(self, change=None): + @observe('security_dir') + def check_security_dir(self, change=None): self._mkdir(self.security_dir, 0o40700) - @observe('pid_dir') - def check_pid_dir(self, change=None): + @observe('pid_dir') + def check_pid_dir(self, change=None): self._mkdir(self.pid_dir, 0o40700) def check_dirs(self): diff --git a/contrib/python/ipython/py2/IPython/core/prompts.py b/contrib/python/ipython/py2/IPython/core/prompts.py index 7802bc5363..cc6bcb721f 100644 --- a/contrib/python/ipython/py2/IPython/core/prompts.py +++ b/contrib/python/ipython/py2/IPython/core/prompts.py @@ -1,8 +1,8 @@ # -*- coding: utf-8 -*- -"""Being removed +"""Being removed """ -from IPython.utils import py3compat +from IPython.utils import py3compat class LazyEvaluate(object): """This is used for formatting strings with values that need to be updated diff --git a/contrib/python/ipython/py2/IPython/core/pylabtools.py b/contrib/python/ipython/py2/IPython/core/pylabtools.py index a1932d8c48..ace18b57e8 100644 --- a/contrib/python/ipython/py2/IPython/core/pylabtools.py +++ b/contrib/python/ipython/py2/IPython/core/pylabtools.py @@ -377,7 +377,7 @@ def configure_inline_support(shell, backend): from ipykernel.pylab.backend_inline import InlineBackend except ImportError: return - import matplotlib + import matplotlib cfg = InlineBackend.instance(parent=shell) cfg.shell = shell @@ -391,9 +391,9 @@ def configure_inline_support(shell, backend): # Save rcParams that will be overwrittern shell._saved_rcParams = dict() for k in cfg.rc: - shell._saved_rcParams[k] = matplotlib.rcParams[k] + shell._saved_rcParams[k] = matplotlib.rcParams[k] # load inline_rc - matplotlib.rcParams.update(cfg.rc) + matplotlib.rcParams.update(cfg.rc) new_backend_name = "inline" else: from ipykernel.pylab.backend_inline import flush_figures @@ -402,7 +402,7 @@ def configure_inline_support(shell, backend): except ValueError: pass if hasattr(shell, '_saved_rcParams'): - matplotlib.rcParams.update(shell._saved_rcParams) + matplotlib.rcParams.update(shell._saved_rcParams) del shell._saved_rcParams new_backend_name = "other" diff --git a/contrib/python/ipython/py2/IPython/core/release.py b/contrib/python/ipython/py2/IPython/core/release.py index 94dea1073b..127e59629f 100644 --- a/contrib/python/ipython/py2/IPython/core/release.py +++ b/contrib/python/ipython/py2/IPython/core/release.py @@ -19,11 +19,11 @@ name = 'ipython' # IPython version information. An empty _version_extra corresponds to a full # release. 'dev' as a _version_extra string means this is a development # version -_version_major = 5 +_version_major = 5 _version_minor = 9 -_version_patch = 0 +_version_patch = 0 _version_extra = '.dev' -# _version_extra = 'rc1' +# _version_extra = 'rc1' _version_extra = '' # Uncomment this for full releases # release.codename is deprecated in 2.0, will be removed in 3.0 diff --git a/contrib/python/ipython/py2/IPython/core/shellapp.py b/contrib/python/ipython/py2/IPython/core/shellapp.py index 213648246e..0684b41880 100644 --- a/contrib/python/ipython/py2/IPython/core/shellapp.py +++ b/contrib/python/ipython/py2/IPython/core/shellapp.py @@ -24,15 +24,15 @@ from IPython.utils import py3compat from IPython.utils.contexts import preserve_keys from IPython.utils.path import filefind from traitlets import ( - Unicode, Instance, List, Bool, CaselessStrEnum, observe, + Unicode, Instance, List, Bool, CaselessStrEnum, observe, ) -from IPython.terminal import pt_inputhooks +from IPython.terminal import pt_inputhooks #----------------------------------------------------------------------------- # Aliases and Flags #----------------------------------------------------------------------------- -gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases)) +gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases)) backend_keys = sorted(pylabtools.backends.keys()) backend_keys.insert(0, 'auto') @@ -102,7 +102,7 @@ shell_aliases['cache-size'] = 'InteractiveShell.cache_size' class InteractiveShellApp(Configurable): """A Mixin for applications that start InteractiveShell instances. - + Provides configurables for loading extensions and executing files as part of configuring a Shell environment. @@ -115,73 +115,73 @@ class InteractiveShellApp(Configurable): - :meth:`init_extensions` - :meth:`init_code` """ - extensions = List(Unicode(), + extensions = List(Unicode(), help="A list of dotted module names of IPython extensions to load." - ).tag(config=True) - extra_extension = Unicode('', + ).tag(config=True) + extra_extension = Unicode('', help="dotted module name of an IPython extension to load." - ).tag(config=True) + ).tag(config=True) - reraise_ipython_extension_failures = Bool(False, + reraise_ipython_extension_failures = Bool(False, help="Reraise exceptions encountered loading IPython extensions?", - ).tag(config=True) + ).tag(config=True) # Extensions that are always loaded (not configurable) - default_extensions = List(Unicode(), [u'storemagic']).tag(config=False) - - hide_initial_ns = Bool(True, + default_extensions = List(Unicode(), [u'storemagic']).tag(config=False) + + hide_initial_ns = Bool(True, help="""Should variables loaded at startup (by startup files, exec_lines, etc.) be hidden from tools like %who?""" - ).tag(config=True) + ).tag(config=True) - exec_files = List(Unicode(), + exec_files = List(Unicode(), help="""List of files to run at IPython startup.""" - ).tag(config=True) - exec_PYTHONSTARTUP = Bool(True, + ).tag(config=True) + exec_PYTHONSTARTUP = Bool(True, help="""Run the file referenced by the PYTHONSTARTUP environment variable at IPython startup.""" - ).tag(config=True) - file_to_run = Unicode('', - help="""A file to be run""").tag(config=True) + ).tag(config=True) + file_to_run = Unicode('', + help="""A file to be run""").tag(config=True) - exec_lines = List(Unicode(), + exec_lines = List(Unicode(), help="""lines of code to run at IPython startup.""" - ).tag(config=True) - code_to_run = Unicode('', + ).tag(config=True) + code_to_run = Unicode('', help="Execute the given command string." - ).tag(config=True) - module_to_run = Unicode('', + ).tag(config=True) + module_to_run = Unicode('', help="Run the module as a script." - ).tag(config=True) - gui = CaselessStrEnum(gui_keys, allow_none=True, + ).tag(config=True) + gui = CaselessStrEnum(gui_keys, allow_none=True, help="Enable GUI event loop integration with any of {0}.".format(gui_keys) - ).tag(config=True) + ).tag(config=True) matplotlib = CaselessStrEnum(backend_keys, allow_none=True, help="""Configure matplotlib for interactive use with the default matplotlib backend.""" - ).tag(config=True) + ).tag(config=True) pylab = CaselessStrEnum(backend_keys, allow_none=True, help="""Pre-load matplotlib and numpy for interactive use, selecting a particular matplotlib backend and loop integration. """ - ).tag(config=True) - pylab_import_all = Bool(True, + ).tag(config=True) + pylab_import_all = Bool(True, help="""If true, IPython will populate the user namespace with numpy, pylab, etc. and an ``import *`` is done from numpy and pylab, when using pylab mode. - + When False, pylab mode should not import any names into the user namespace. """ - ).tag(config=True) + ).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) - # whether interact-loop should start - interact = Bool(True) - + # whether interact-loop should start + interact = Bool(True) + user_ns = Instance(dict, args=None, allow_none=True) - @observe('user_ns') - def _user_ns_changed(self, change): + @observe('user_ns') + def _user_ns_changed(self, change): if self.shell is not None: - self.shell.user_ns = change['new'] + self.shell.user_ns = change['new'] self.shell.init_user_ns() def init_path(self): @@ -205,10 +205,10 @@ class InteractiveShellApp(Configurable): elif self.gui: enable = shell.enable_gui key = self.gui - + if not enable: return - + try: r = enable(key) except ImportError: @@ -219,7 +219,7 @@ class InteractiveShellApp(Configurable): self.log.warning("GUI event loop or pylab initialization failed") self.shell.showtraceback() return - + if isinstance(r, tuple): gui, backend = r[:2] self.log.info("Enabling GUI event loop integration, " @@ -265,16 +265,16 @@ class InteractiveShellApp(Configurable): self._run_startup_files() self._run_exec_lines() self._run_exec_files() - + # Hide variables defined here from %who etc. if self.hide_initial_ns: self.shell.user_ns_hidden.update(self.shell.user_ns) - + # command-line execution (ipython -i script.py, ipython -m module) # should *not* be excluded from %whos self._run_cmd_line_code() self._run_module() - + # flush output, so itwon't be attached to the first cell sys.stdout.flush() sys.stderr.flush() @@ -301,7 +301,7 @@ class InteractiveShellApp(Configurable): def _exec_file(self, fname, shell_futures=False): try: full_filename = filefind(fname, [u'.', self.ipython_dir]) - except IOError: + except IOError: self.log.warning("File not found: %r"%fname) return # Make sure that the running script gets a proper sys.argv as if it @@ -337,7 +337,7 @@ class InteractiveShellApp(Configurable): os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS) ] startup_files = [] - + if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \ not (self.file_to_run or self.code_to_run or self.module_to_run): python_startup = os.environ['PYTHONSTARTUP'] @@ -352,7 +352,7 @@ class InteractiveShellApp(Configurable): startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) if not startup_files: return - + self.log.debug("Running startup files from %s...", startup_dir) try: for fname in sorted(startup_files): @@ -386,20 +386,20 @@ class InteractiveShellApp(Configurable): self.log.warning("Error in executing line in user namespace: %s" % line) self.shell.showtraceback() - if not self.interact: - self.exit(1) + if not self.interact: + self.exit(1) # Like Python itself, ignore the second if the first of these is present elif self.file_to_run: fname = self.file_to_run - if os.path.isdir(fname): - fname = os.path.join(fname, "__main__.py") + if os.path.isdir(fname): + fname = os.path.join(fname, "__main__.py") try: self._exec_file(fname, shell_futures=True) except: self.shell.showtraceback(tb_offset=4) - if not self.interact: - self.exit(1) + if not self.interact: + self.exit(1) def _run_module(self): """Run module specified at the command-line.""" diff --git a/contrib/python/ipython/py2/IPython/core/ultratb.py b/contrib/python/ipython/py2/IPython/core/ultratb.py index a855145825..f327943eb8 100644 --- a/contrib/python/ipython/py2/IPython/core/ultratb.py +++ b/contrib/python/ipython/py2/IPython/core/ultratb.py @@ -38,12 +38,12 @@ Give it a shot--you'll love it or you'll hate it. variables (but otherwise includes the information and context given by Verbose). -.. note:: - - The verbose mode print all variables in the stack, which means it can - potentially leak sensitive information like access keys, or unencryted - password. +.. note:: + The verbose mode print all variables in the stack, which means it can + potentially leak sensitive information like access keys, or unencryted + password. + Installation instructions for VerboseTB:: import sys,ultratb @@ -67,9 +67,9 @@ ColorSchemeTable class. Currently the following exist: - LightBG: similar to Linux but swaps dark/light colors to be more readable in light background terminals. - - Neutral: a neutral color scheme that should be readable on both light and - dark background - + - Neutral: a neutral color scheme that should be readable on both light and + dark background + You can implement other color schemes easily, the syntax is fairly self-explanatory. Please send back new schemes you develop to the author for possible inclusion in future releases. @@ -88,7 +88,7 @@ Inheritance diagram: # the file COPYING, distributed as part of this software. #***************************************************************************** -from __future__ import absolute_import +from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function @@ -125,11 +125,11 @@ from IPython.utils import path as util_path from IPython.utils import py3compat from IPython.utils import ulinecache from IPython.utils.data import uniq_stable -from IPython.utils.terminal import get_terminal_size -from logging import info, error - -import IPython.utils.colorable as colorable +from IPython.utils.terminal import get_terminal_size +from logging import info, error +import IPython.utils.colorable as colorable + # Globals # amount of space to put line numbers before verbose tracebacks INDENT_SIZE = 8 @@ -226,8 +226,8 @@ def findsource(object): # the length of lines, which causes an error. Safeguard against that. lnum = min(object.co_firstlineno, len(lines)) - 1 while lnum > 0: - if pmatch(lines[lnum]): - break + if pmatch(lines[lnum]): + break lnum -= 1 return lines, lnum @@ -283,11 +283,11 @@ def getargs(co): remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] - if not remain: - break + if not remain: + break remain[-1] = remain[-1] - 1 - if not remain: - break + if not remain: + break args[i] = stack[0] varargs = None @@ -413,7 +413,7 @@ def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None) if i == lnum: # This is the line with the error pad = numbers_width - len(str(i)) - num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) + num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) line = '%s%s%s %s%s' % (Colors.linenoEm, num, Colors.line, line, Colors.Normal) else: @@ -481,22 +481,22 @@ def find_recursion(etype, value, records): #--------------------------------------------------------------------------- # Module classes -class TBTools(colorable.Colorable): +class TBTools(colorable.Colorable): """Basic tools used by all traceback printer classes.""" # Number of frames to skip when reporting tracebacks tb_offset = 0 - def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): + def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): # Whether to call the interactive pdb debugger after printing # tracebacks or not - super(TBTools, self).__init__(parent=parent, config=config) + super(TBTools, self).__init__(parent=parent, config=config) self.call_pdb = call_pdb # Output stream to write to. Note that we store the original value in # a private attribute and then make the public ostream a property, so - # that we can delay accessing sys.stdout until runtime. The way - # things are written now, the sys.stdout object is dynamically managed + # that we can delay accessing sys.stdout until runtime. The way + # things are written now, the sys.stdout object is dynamically managed # so a reference to it should NEVER be stored statically. This # property approach confines this detail to a single location, and all # subclasses can simply access self.ostream for writing. @@ -509,7 +509,7 @@ class TBTools(colorable.Colorable): self.old_scheme = color_scheme # save initial value for toggles if call_pdb: - self.pdb = debugger.Pdb() + self.pdb = debugger.Pdb() else: self.pdb = None @@ -519,12 +519,12 @@ class TBTools(colorable.Colorable): Valid values are: - None: the default, which means that IPython will dynamically resolve - to sys.stdout. This ensures compatibility with most tools, including + to sys.stdout. This ensures compatibility with most tools, including Windows (where plain stdout doesn't recognize ANSI escapes). - Any object with 'write' and 'flush' attributes. """ - return sys.stdout if self._ostream is None else self._ostream + return sys.stdout if self._ostream is None else self._ostream def _set_ostream(self, val): assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) @@ -596,9 +596,9 @@ class ListTB(TBTools): Because they are meant to be called without a full traceback (only a list), instances of this class can't call the interactive pdb debugger.""" - def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None): + def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None): TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, - ostream=ostream, parent=parent) + ostream=ostream, parent=parent) def __call__(self, etype, value, elist): self.ostream.flush() @@ -711,10 +711,10 @@ class ListTB(TBTools): have_filedata = False Colors = self.Colors list = [] - stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) + stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) if value is None: # Not sure if this can still happen in Python 2.6 and above - list.append(stype + '\n') + list.append(stype + '\n') else: if issubclass(etype, SyntaxError): have_filedata = True @@ -754,10 +754,10 @@ class ListTB(TBTools): except Exception: s = self._some_str(value) if s: - list.append('%s%s:%s %s\n' % (stype, Colors.excName, + list.append('%s%s:%s %s\n' % (stype, Colors.excName, Colors.Normal, s)) else: - list.append('%s\n' % stype) + list.append('%s\n' % stype) # sync with user hooks if have_filedata: @@ -795,9 +795,9 @@ class ListTB(TBTools): def _some_str(self, value): # Lifted from traceback.py try: - return py3compat.cast_unicode(str(value)) + return py3compat.cast_unicode(str(value)) except: - return u'<unprintable %s object>' % type(value).__name__ + return u'<unprintable %s object>' % type(value).__name__ #---------------------------------------------------------------------------- @@ -811,7 +811,7 @@ class VerboseTB(TBTools): def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=True, - check_cache=None, debugger_cls = None): + check_cache=None, debugger_cls = None): """Specify traceback offset, headers and color scheme. Define how many frames to drop from the tracebacks. Calling it with @@ -832,8 +832,8 @@ class VerboseTB(TBTools): check_cache = linecache.checkcache self.check_cache = check_cache - self.debugger_cls = debugger_cls or debugger.Pdb - + self.debugger_cls = debugger_cls or debugger.Pdb + def format_records(self, records, last_unique, recursion_repeat): """Format the stack frames of the traceback""" frames = [] @@ -929,12 +929,12 @@ class VerboseTB(TBTools): elif file.endswith(('.pyc', '.pyo')): # Look up the corresponding source file. - try: - file = openpy.source_from_cache(file) - except ValueError: - # Failed to get the source file for some reason - # E.g. https://github.com/ipython/ipython/issues/9486 - return '%s %s\n' % (link, call) + try: + file = openpy.source_from_cache(file) + except ValueError: + # Failed to get the source file for some reason + # E.g. https://github.com/ipython/ipython/issues/9486 + return '%s %s\n' % (link, call) def linereader(file=file, lnum=[lnum], getline=ulinecache.getline): line = getline(file, lnum[0]) @@ -1038,21 +1038,21 @@ class VerboseTB(TBTools): colors = self.Colors # just a shorthand + quicker name lookup colorsnormal = colors.Normal # used a lot exc = '%s%s%s' % (colors.excName, etype, colorsnormal) - width = min(75, get_terminal_size()[0]) + width = min(75, get_terminal_size()[0]) if long_version: # Header with the exception type, python version, and date pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) - head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, - exc, ' ' * (width - len(str(etype)) - len(pyver)), - pyver, date.rjust(width) ) + head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, + exc, ' ' * (width - len(str(etype)) - len(pyver)), + pyver, date.rjust(width) ) head += "\nA problem occurred executing Python code. Here is the sequence of function" \ "\ncalls leading up to the error, with the most recent (innermost) call last." else: # Simplified header head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ - rjust(width - len(str(etype))) ) + rjust(width - len(str(etype))) ) return head @@ -1171,7 +1171,7 @@ class VerboseTB(TBTools): colors = self.Colors # just a shorthand + quicker name lookup colorsnormal = colors.Normal # used a lot - head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) + head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) structured_traceback_parts = [head] if py3compat.PY3: chained_exceptions_tb_offset = 0 @@ -1287,7 +1287,7 @@ class FormattedTB(VerboseTB, ListTB): def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=False, - check_cache=None, debugger_cls=None): + check_cache=None, debugger_cls=None): # NEVER change the order of this list. Put new modes at the end: self.valid_modes = ['Plain', 'Context', 'Verbose'] @@ -1296,7 +1296,7 @@ class FormattedTB(VerboseTB, ListTB): VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, ostream=ostream, tb_offset=tb_offset, long_header=long_header, include_vars=include_vars, - check_cache=check_cache, debugger_cls=debugger_cls) + check_cache=check_cache, debugger_cls=debugger_cls) # Different types of tracebacks are joined with different separators to # form a single string. They are taken from this dict @@ -1446,7 +1446,7 @@ class SyntaxTB(ListTB): newtext = ulinecache.getline(value.filename, value.lineno) if newtext: value.text = newtext - self.last_syntax_error = value + self.last_syntax_error = value return super(SyntaxTB, self).structured_traceback(etype, value, elist, tb_offset=tb_offset, context=context) diff --git a/contrib/python/ipython/py2/IPython/core/usage.py b/contrib/python/ipython/py2/IPython/core/usage.py index c4d3c16eca..26506281a7 100644 --- a/contrib/python/ipython/py2/IPython/core/usage.py +++ b/contrib/python/ipython/py2/IPython/core/usage.py @@ -114,7 +114,7 @@ MAIN FEATURES your history for lines that match what you've typed so far, completing as much as it can. - - %hist: search history by index. + - %hist: search history by index. * Persistent command history across sessions. @@ -337,9 +337,9 @@ default_banner_parts = [ default_banner = ''.join(default_banner_parts) -# deprecated GUI banner +# deprecated GUI banner -default_gui_banner = '\n'.join([ - 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed', - default_banner, -]) +default_gui_banner = '\n'.join([ + 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed', + default_banner, +]) |