diff options
author | smosker <smosker@yandex-team.ru> | 2022-02-10 16:48:21 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:48:21 +0300 |
commit | dd14d17a747a9c259858faf2fcc3ea6b92df4e15 (patch) | |
tree | f332cd81782832c17c48d8c3b4511924cd9e47fd /contrib/python/ipython | |
parent | b637e2fa3213638fbabe52c15dad14c8237945ac (diff) | |
download | ydb-dd14d17a747a9c259858faf2fcc3ea6b92df4e15.tar.gz |
Restoring authorship annotation for <smosker@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/python/ipython')
63 files changed, 1446 insertions, 1446 deletions
diff --git a/contrib/python/ipython/py2/IPython/config.py b/contrib/python/ipython/py2/IPython/config.py index cf2bacafad..95aacd6b9f 100644 --- a/contrib/python/ipython/py2/IPython/config.py +++ b/contrib/python/ipython/py2/IPython/config.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.config` package has been deprecated since IPython 4.0. " +warn("The `IPython.config` package has been deprecated since IPython 4.0. " "You should import from traitlets.config instead.", ShimWarning) diff --git a/contrib/python/ipython/py2/IPython/core/application.py b/contrib/python/ipython/py2/IPython/core/application.py index af28133945..f6d002a06d 100644 --- a/contrib/python/ipython/py2/IPython/core/application.py +++ b/contrib/python/ipython/py2/IPython/core/application.py @@ -44,14 +44,14 @@ else: "/etc/ipython", ] - -ENV_CONFIG_DIRS = [] -_env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython') -if _env_config_dir not in SYSTEM_CONFIG_DIRS: - # only add ENV_CONFIG if sys.prefix is not already included - ENV_CONFIG_DIRS.append(_env_config_dir) - - + +ENV_CONFIG_DIRS = [] +_env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython') +if _env_config_dir not in SYSTEM_CONFIG_DIRS: + # only add ENV_CONFIG if sys.prefix is not already included + ENV_CONFIG_DIRS.append(_env_config_dir) + + _envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS') if _envvar in {None, ''}: IPYTHON_SUPPRESS_CONFIG_ERRORS = None @@ -411,7 +411,7 @@ class BaseIPythonApplication(Application): def init_config_files(self): """[optionally] copy default config files into profile dir.""" - self.config_file_paths.extend(ENV_CONFIG_DIRS) + self.config_file_paths.extend(ENV_CONFIG_DIRS) self.config_file_paths.extend(SYSTEM_CONFIG_DIRS) # copy config files path = self.builtin_profile_dir diff --git a/contrib/python/ipython/py2/IPython/core/compilerop.py b/contrib/python/ipython/py2/IPython/core/compilerop.py index f529eb5224..0e8f094e31 100644 --- a/contrib/python/ipython/py2/IPython/core/compilerop.py +++ b/contrib/python/ipython/py2/IPython/core/compilerop.py @@ -56,7 +56,7 @@ def code_name(code, number=0): This now expects code to be unicode. """ - hash_digest = hashlib.sha1(code.encode("utf-8")).hexdigest() + hash_digest = hashlib.sha1(code.encode("utf-8")).hexdigest() # Include the number and 12 characters of the hash in the name. It's # pretty much impossible that in a single session we'll have collisions # even with truncated hashes, and the full one makes tracebacks too long diff --git a/contrib/python/ipython/py2/IPython/core/completer.py b/contrib/python/ipython/py2/IPython/core/completer.py index b386945e54..a8aaf1080b 100644 --- a/contrib/python/ipython/py2/IPython/core/completer.py +++ b/contrib/python/ipython/py2/IPython/core/completer.py @@ -25,7 +25,7 @@ import re import sys import unicodedata import string -import warnings +import warnings from traitlets.config.configurable import Configurable from IPython.core.error import TryNext @@ -47,9 +47,9 @@ if sys.platform == 'win32': else: PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' -# Protect against returning an enormous number of completions which the frontend -# may have trouble processing. -MATCHES_LIMIT = 500 +# Protect against returning an enormous number of completions which the frontend +# may have trouble processing. +MATCHES_LIMIT = 500 def has_open_quotes(s): """Return whether a string has open quotes. @@ -243,11 +243,11 @@ class Completer(Configurable): """ ).tag(config=True) - backslash_combining_completions = Bool(True, - help="Enable unicode completions, e.g. \\alpha<tab> . " - "Includes completion of latex commands, unicode names, and expanding " - "unicode characters back to latex commands.").tag(config=True) - + backslash_combining_completions = Bool(True, + help="Enable unicode completions, e.g. \\alpha<tab> . " + "Includes completion of latex commands, unicode names, and expanding " + "unicode characters back to latex commands.").tag(config=True) + def __init__(self, namespace=None, global_namespace=None, **kwargs): """Create a new completer for the command line. @@ -549,13 +549,13 @@ class IPCompleter(Completer): """, ).tag(config=True) - @observe('limit_to__all__') - def _limit_to_all_changed(self, change): - warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' - 'value has been deprecated since IPython 5.0, will be made to have ' - 'no effects and then removed in future version of IPython.', - UserWarning) - + @observe('limit_to__all__') + def _limit_to_all_changed(self, change): + warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' + 'value has been deprecated since IPython 5.0, will be made to have ' + 'no effects and then removed in future version of IPython.', + UserWarning) + def __init__(self, shell=None, namespace=None, global_namespace=None, use_readline=True, config=None, **kwargs): """IPCompleter() -> completer @@ -1093,12 +1093,12 @@ class IPCompleter(Completer): return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] except TryNext: pass - except KeyboardInterrupt: - """ - If custom completer take too long, - let keyboard interrupt abort and return nothing. - """ - break + except KeyboardInterrupt: + """ + If custom completer take too long, + let keyboard interrupt abort and return nothing. + """ + break return None @@ -1137,21 +1137,21 @@ class IPCompleter(Completer): if cursor_pos is None: cursor_pos = len(line_buffer) if text is None else len(text) - if self.use_main_ns: - self.namespace = __main__.__dict__ - - if PY3 and self.backslash_combining_completions: + if self.use_main_ns: + self.namespace = __main__.__dict__ + if PY3 and self.backslash_combining_completions: + base_text = text if not line_buffer else line_buffer[:cursor_pos] latex_text, latex_matches = self.latex_matches(base_text) if latex_matches: - return latex_text, latex_matches + return latex_text, latex_matches name_text = '' name_matches = [] for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): name_text, name_matches = meth(base_text) if name_text: - return name_text, name_matches[:MATCHES_LIMIT] + return name_text, name_matches[:MATCHES_LIMIT] # if text is either None or an empty string, rely on the line buffer if not text: @@ -1192,6 +1192,6 @@ class IPCompleter(Completer): # different types of objects. The rlcomplete() method could then # simply collapse the dict into a list for readline, but we'd have # richer completion semantics in other evironments. - self.matches = sorted(set(self.matches), key=completions_sorting_key)[:MATCHES_LIMIT] + self.matches = sorted(set(self.matches), key=completions_sorting_key)[:MATCHES_LIMIT] return text, self.matches diff --git a/contrib/python/ipython/py2/IPython/core/completerlib.py b/contrib/python/ipython/py2/IPython/core/completerlib.py index e736ca73d1..a41f1c4af9 100644 --- a/contrib/python/ipython/py2/IPython/core/completerlib.py +++ b/contrib/python/ipython/py2/IPython/core/completerlib.py @@ -164,11 +164,11 @@ def get_root_modules(): ip.db['rootmodules_cache'] maps sys.path entries to list of modules. """ ip = get_ipython() - if ip is None: - # No global shell instance to store cached list of modules. - # Don't try to scan for modules every time. - return list(sys.builtin_module_names) - + if ip is None: + # No global shell instance to store cached list of modules. + # Don't try to scan for modules every time. + return list(sys.builtin_module_names) + rootmodules_cache = ip.db.get('rootmodules_cache', {}) rootmodules = list(sys.builtin_module_names) start_time = time() @@ -207,7 +207,7 @@ def is_importable(module, attr, only_modules): return not(attr[:2] == '__' and attr[-2:] == '__') def try_import(mod, only_modules=False): - mod = mod.rstrip('.') + mod = mod.rstrip('.') try: m = __import__(mod) except: diff --git a/contrib/python/ipython/py2/IPython/core/crashhandler.py b/contrib/python/ipython/py2/IPython/core/crashhandler.py index 22bbd7ae81..a6dededada 100644 --- a/contrib/python/ipython/py2/IPython/core/crashhandler.py +++ b/contrib/python/ipython/py2/IPython/core/crashhandler.py @@ -54,16 +54,16 @@ with the subject '{app_name} Crash Report'. If you want to do it now, the following command will work (under Unix): mail -s '{app_name} Crash Report' {contact_email} < {crash_report_fname} -In your email, please also include information about: -- The operating system under which the crash happened: Linux, macOS, Windows, - other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2, - Windows 10 Pro), and whether it is 32-bit or 64-bit; -- How {app_name} was installed: using pip or conda, from GitHub, as part of - a Docker container, or other, providing more detail if possible; -- How to reproduce the crash: what exact sequence of instructions can one - input to get the same crash? Ideally, find a minimal yet complete sequence - of instructions that yields the crash. - +In your email, please also include information about: +- The operating system under which the crash happened: Linux, macOS, Windows, + other, and which exact version (for example: Ubuntu 16.04.3, macOS 10.13.2, + Windows 10 Pro), and whether it is 32-bit or 64-bit; +- How {app_name} was installed: using pip or conda, from GitHub, as part of + a Docker container, or other, providing more detail if possible; +- How to reproduce the crash: what exact sequence of instructions can one + input to get the same crash? Ideally, find a minimal yet complete sequence + of instructions that yields the crash. + To ensure accurate tracking of this issue, please file a report about it at: {bug_tracker} """ diff --git a/contrib/python/ipython/py2/IPython/core/debugger.py b/contrib/python/ipython/py2/IPython/core/debugger.py index f08cfb1a78..a2f6200b31 100644 --- a/contrib/python/ipython/py2/IPython/core/debugger.py +++ b/contrib/python/ipython/py2/IPython/core/debugger.py @@ -13,8 +13,8 @@ The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor changes. Licensing should therefore be under the standard Python terms. For details on the PSF (Python Software Foundation) standard license, see: -https://docs.python.org/2/license.html -""" +https://docs.python.org/2/license.html +""" #***************************************************************************** # @@ -65,7 +65,7 @@ def BdbQuit_excepthook(et, ev, tb, excepthook=None): parameter. """ warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1", - DeprecationWarning, stacklevel=2) + DeprecationWarning, stacklevel=2) if et==bdb.BdbQuit: print('Exiting Debugger.') elif excepthook is not None: @@ -78,7 +78,7 @@ def BdbQuit_excepthook(et, ev, tb, excepthook=None): def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): warnings.warn( "`BdbQuit_IPython_excepthook` is deprecated since version 5.1", - DeprecationWarning, stacklevel=2) + DeprecationWarning, stacklevel=2) print('Exiting Debugger.') @@ -130,7 +130,7 @@ class Tracer(object): """ warnings.warn("`Tracer` is deprecated since version 5.1, directly use " "`IPython.core.debugger.Pdb.set_trace()`", - DeprecationWarning, stacklevel=2) + DeprecationWarning, stacklevel=2) ip = get_ipython() if ip is None: @@ -203,7 +203,7 @@ def _file_lines(fname): return out -class Pdb(OldPdb): +class Pdb(OldPdb): """Modified Pdb class, does not load readline. for a standalone version that uses prompt_toolkit, see @@ -228,14 +228,14 @@ class Pdb(OldPdb): self.shell = get_ipython() if self.shell is None: - save_main = sys.modules['__main__'] + save_main = sys.modules['__main__'] # No IPython instance running, we must create one from IPython.terminal.interactiveshell import \ TerminalInteractiveShell self.shell = TerminalInteractiveShell.instance() - # needed by any code which calls __import__("__main__") after - # the debugger was entered. See also #9941. - sys.modules['__main__'] = save_main + # needed by any code which calls __import__("__main__") after + # the debugger was entered. See also #9941. + sys.modules['__main__'] = save_main if color_scheme is not None: warnings.warn( @@ -485,8 +485,8 @@ class Pdb(OldPdb): pass def do_list(self, arg): - """Print lines of code from the current stack frame - """ + """Print lines of code from the current stack frame + """ self.lastcmd = 'list' last = None if arg: @@ -530,10 +530,10 @@ class Pdb(OldPdb): return inspect.getblock(lines[lineno:]), lineno+1 def do_longlist(self, arg): - """Print lines of code from the current stack frame. - - Shows more lines than 'list' does. - """ + """Print lines of code from the current stack frame. + + Shows more lines than 'list' does. + """ self.lastcmd = 'longlist' try: lines, lineno = self.getsourcelines(self.curframe) @@ -607,12 +607,12 @@ class Pdb(OldPdb): self.print_stack_trace() do_w = do_where - - -def set_trace(frame=None): - """ - Start debugging from `frame`. - - If frame is not specified, debugging starts from caller's frame. - """ - Pdb().set_trace(frame or sys._getframe().f_back) + + +def set_trace(frame=None): + """ + Start debugging from `frame`. + + If frame is not specified, debugging starts from caller's frame. + """ + Pdb().set_trace(frame or sys._getframe().f_back) diff --git a/contrib/python/ipython/py2/IPython/core/display.py b/contrib/python/ipython/py2/IPython/core/display.py index 5c82a57b31..c696f6c831 100644 --- a/contrib/python/ipython/py2/IPython/core/display.py +++ b/contrib/python/ipython/py2/IPython/core/display.py @@ -11,7 +11,7 @@ try: except ImportError: from base64 import encodestring as base64_encode -from binascii import b2a_hex, hexlify +from binascii import b2a_hex, hexlify import json import mimetypes import os @@ -26,9 +26,9 @@ from IPython.testing.skipdoctest import skip_doctest __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', -'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', 'Javascript', +'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close', -'publish_display_data', 'update_display', 'DisplayHandle'] +'publish_display_data', 'update_display', 'DisplayHandle'] #----------------------------------------------------------------------------- # utility functions @@ -79,8 +79,8 @@ def _display_mimetype(mimetype, objs, raw=False, metadata=None): #----------------------------------------------------------------------------- # Main functions #----------------------------------------------------------------------------- -# use * to indicate transient is keyword-only -def publish_display_data(data, metadata=None, source=None, **kwargs): +# use * to indicate transient is keyword-only +def publish_display_data(data, metadata=None, source=None, **kwargs): """Publish data and metadata to all frontends. See the ``display_data`` message in the messaging documentation for @@ -115,38 +115,38 @@ def publish_display_data(data, metadata=None, source=None, **kwargs): to specify metadata about particular representations. source : str, deprecated Unused. - transient : dict, keyword-only - A dictionary of transient data, such as display_id. + transient : dict, keyword-only + A dictionary of transient data, such as display_id. """ from IPython.core.interactiveshell import InteractiveShell - - display_pub = InteractiveShell.instance().display_pub - - # only pass transient if supplied, - # to avoid errors with older ipykernel. - # TODO: We could check for ipykernel version and provide a detailed upgrade message. - - display_pub.publish( + + display_pub = InteractiveShell.instance().display_pub + + # only pass transient if supplied, + # to avoid errors with older ipykernel. + # TODO: We could check for ipykernel version and provide a detailed upgrade message. + + display_pub.publish( data=data, metadata=metadata, - **kwargs + **kwargs ) - -def _new_id(): - """Generate a new random text id with urandom""" - return b2a_hex(os.urandom(16)).decode('ascii') - - + +def _new_id(): + """Generate a new random text id with urandom""" + return b2a_hex(os.urandom(16)).decode('ascii') + + def display(*objs, **kwargs): """Display a Python object in all frontends. By default all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how. - In terminal IPython this will be similar to using :func:`print`, for use in richer - frontends see Jupyter notebook examples with rich display logic. - + In terminal IPython this will be similar to using :func:`print`, for use in richer + frontends see Jupyter notebook examples with rich display logic. + Parameters ---------- objs : tuple of objects @@ -154,11 +154,11 @@ def display(*objs, **kwargs): raw : bool, optional Are the objects to be displayed already mimetype-keyed dicts of raw display data, or Python objects that need to be formatted before display? [default: False] - include : list, tuple or set, optional + include : list, tuple or set, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. - exclude : list, tuple or set, optional + exclude : list, tuple or set, optional A list of format type strings (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument. @@ -166,147 +166,147 @@ def display(*objs, **kwargs): A dictionary of metadata to associate with the output. mime-type keys in this dictionary will be associated with the individual representation formats, if they exist. - transient : dict, optional - A dictionary of transient data to associate with the output. - Data in this dict should not be persisted to files (e.g. notebooks). - display_id : str, bool optional - Set an id for the display. - This id can be used for updating this display area later via update_display. - If given as `True`, generate a new `display_id` - kwargs: additional keyword-args, optional - Additional keyword-arguments are passed through to the display publisher. - - Returns - ------- - - handle: DisplayHandle - Returns a handle on updatable displays for use with :func:`update_display`, - if `display_id` is given. Returns :any:`None` if no `display_id` is given - (default). - - Examples - -------- - - >>> class Json(object): - ... def __init__(self, json): - ... self.json = json - ... def _repr_pretty_(self, pp, cycle): - ... import json - ... pp.text(json.dumps(self.json, indent=2)) - ... def __repr__(self): - ... return str(self.json) - ... - - >>> d = Json({1:2, 3: {4:5}}) - - >>> print(d) - {1: 2, 3: {4: 5}} - - >>> display(d) - { - "1": 2, - "3": { - "4": 5 - } - } - - >>> def int_formatter(integer, pp, cycle): - ... pp.text('I'*integer) - - >>> plain = get_ipython().display_formatter.formatters['text/plain'] - >>> plain.for_type(int, int_formatter) - <function _repr_pprint at 0x...> - >>> display(7-5) - II - - >>> del plain.type_printers[int] - >>> display(7-5) - 2 - - See Also - -------- - - :func:`update_display` - - Notes - ----- - - In Python, objects can declare their textual representation using the - `__repr__` method. IPython expands on this idea and allows objects to declare - other, rich representations including: - - - HTML - - JSON - - PNG - - JPEG - - SVG - - LaTeX - - A single object can declare some or all of these representations; all are - handled by IPython's display system. - - The main idea of the first approach is that you have to implement special - display methods when you define your class, one for each representation you - want to use. Here is a list of the names of the special methods and the - values they must return: - - - `_repr_html_`: return raw HTML as a string - - `_repr_json_`: return a JSONable dict - - `_repr_jpeg_`: return raw JPEG data - - `_repr_png_`: return raw PNG data - - `_repr_svg_`: return raw SVG data as a string - - `_repr_latex_`: return LaTeX commands in a string surrounded by "$". - - `_repr_mimebundle_`: return a full mimebundle containing the mapping - from all mimetypes to data - - When you are directly writing your own classes, you can adapt them for - display in IPython by following the above approach. But in practice, you - often need to work with existing classes that you can't easily modify. - - You can refer to the documentation on IPython display formatters in order to - register custom formatters for already existing types. - - .. versionadded:: 5.4 display available without import - .. versionadded:: 6.1 display available without import - - Since IPython 5.4 and 6.1 :func:`display` is automatically made available to - the user without import. If you are using display in a document that might - be used in a pure python context or with older version of IPython, use the - following import at the top of your file:: - - from IPython.display import display - + transient : dict, optional + A dictionary of transient data to associate with the output. + Data in this dict should not be persisted to files (e.g. notebooks). + display_id : str, bool optional + Set an id for the display. + This id can be used for updating this display area later via update_display. + If given as `True`, generate a new `display_id` + kwargs: additional keyword-args, optional + Additional keyword-arguments are passed through to the display publisher. + + Returns + ------- + + handle: DisplayHandle + Returns a handle on updatable displays for use with :func:`update_display`, + if `display_id` is given. Returns :any:`None` if no `display_id` is given + (default). + + Examples + -------- + + >>> class Json(object): + ... def __init__(self, json): + ... self.json = json + ... def _repr_pretty_(self, pp, cycle): + ... import json + ... pp.text(json.dumps(self.json, indent=2)) + ... def __repr__(self): + ... return str(self.json) + ... + + >>> d = Json({1:2, 3: {4:5}}) + + >>> print(d) + {1: 2, 3: {4: 5}} + + >>> display(d) + { + "1": 2, + "3": { + "4": 5 + } + } + + >>> def int_formatter(integer, pp, cycle): + ... pp.text('I'*integer) + + >>> plain = get_ipython().display_formatter.formatters['text/plain'] + >>> plain.for_type(int, int_formatter) + <function _repr_pprint at 0x...> + >>> display(7-5) + II + + >>> del plain.type_printers[int] + >>> display(7-5) + 2 + + See Also + -------- + + :func:`update_display` + + Notes + ----- + + In Python, objects can declare their textual representation using the + `__repr__` method. IPython expands on this idea and allows objects to declare + other, rich representations including: + + - HTML + - JSON + - PNG + - JPEG + - SVG + - LaTeX + + A single object can declare some or all of these representations; all are + handled by IPython's display system. + + The main idea of the first approach is that you have to implement special + display methods when you define your class, one for each representation you + want to use. Here is a list of the names of the special methods and the + values they must return: + + - `_repr_html_`: return raw HTML as a string + - `_repr_json_`: return a JSONable dict + - `_repr_jpeg_`: return raw JPEG data + - `_repr_png_`: return raw PNG data + - `_repr_svg_`: return raw SVG data as a string + - `_repr_latex_`: return LaTeX commands in a string surrounded by "$". + - `_repr_mimebundle_`: return a full mimebundle containing the mapping + from all mimetypes to data + + When you are directly writing your own classes, you can adapt them for + display in IPython by following the above approach. But in practice, you + often need to work with existing classes that you can't easily modify. + + You can refer to the documentation on IPython display formatters in order to + register custom formatters for already existing types. + + .. versionadded:: 5.4 display available without import + .. versionadded:: 6.1 display available without import + + Since IPython 5.4 and 6.1 :func:`display` is automatically made available to + the user without import. If you are using display in a document that might + be used in a pure python context or with older version of IPython, use the + following import at the top of your file:: + + from IPython.display import display + """ from IPython.core.interactiveshell import InteractiveShell - - if not InteractiveShell.initialized(): - # Directly print objects. - print(*objs) - return - - raw = kwargs.pop('raw', False) - include = kwargs.pop('include', None) - exclude = kwargs.pop('exclude', None) - metadata = kwargs.pop('metadata', None) - transient = kwargs.pop('transient', None) - display_id = kwargs.pop('display_id', None) - if transient is None: - transient = {} - if display_id: - if display_id is True: - display_id = _new_id() - transient['display_id'] = display_id - if kwargs.get('update') and 'display_id' not in transient: - raise TypeError('display_id required for update_display') - if transient: - kwargs['transient'] = transient + + if not InteractiveShell.initialized(): + # Directly print objects. + print(*objs) + return + + raw = kwargs.pop('raw', False) + include = kwargs.pop('include', None) + exclude = kwargs.pop('exclude', None) + metadata = kwargs.pop('metadata', None) + transient = kwargs.pop('transient', None) + display_id = kwargs.pop('display_id', None) + if transient is None: + transient = {} + if display_id: + if display_id is True: + display_id = _new_id() + transient['display_id'] = display_id + if kwargs.get('update') and 'display_id' not in transient: + raise TypeError('display_id required for update_display') + if transient: + kwargs['transient'] = transient if not raw: format = InteractiveShell.instance().display_formatter.format for obj in objs: if raw: - publish_display_data(data=obj, metadata=metadata, **kwargs) + publish_display_data(data=obj, metadata=metadata, **kwargs) else: format_dict, md_dict = format(obj, include=include, exclude=exclude) if not format_dict: @@ -315,86 +315,86 @@ def display(*objs, **kwargs): if metadata: # kwarg-specified metadata gets precedence _merge(md_dict, metadata) - publish_display_data(data=format_dict, metadata=md_dict, **kwargs) - if display_id: - return DisplayHandle(display_id) - - -# use * for keyword-only display_id arg -def update_display(obj, **kwargs): - """Update an existing display by id - - Parameters - ---------- - - obj: - The object with which to update the display - display_id: keyword-only - The id of the display to update - - See Also - -------- - - :func:`display` - """ - sentinel = object() - display_id = kwargs.pop('display_id', sentinel) - if display_id is sentinel: - raise TypeError("update_display() missing 1 required keyword-only argument: 'display_id'") - kwargs['update'] = True - display(obj, display_id=display_id, **kwargs) - - -class DisplayHandle(object): - """A handle on an updatable display - - Call `.update(obj)` to display a new object. - - Call `.display(obj`) to add a new instance of this display, - and update existing instances. - - See Also - -------- - - :func:`display`, :func:`update_display` - - """ - - def __init__(self, display_id=None): - if display_id is None: - display_id = _new_id() - self.display_id = display_id - - def __repr__(self): - return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) - - def display(self, obj, **kwargs): - """Make a new display with my id, updating existing instances. - - Parameters - ---------- - - obj: - object to display - **kwargs: - additional keyword arguments passed to display - """ - display(obj, display_id=self.display_id, **kwargs) - - def update(self, obj, **kwargs): - """Update existing displays with my id - - Parameters - ---------- - - obj: - object to display - **kwargs: - additional keyword arguments passed to update_display - """ - update_display(obj, display_id=self.display_id, **kwargs) - - + publish_display_data(data=format_dict, metadata=md_dict, **kwargs) + if display_id: + return DisplayHandle(display_id) + + +# use * for keyword-only display_id arg +def update_display(obj, **kwargs): + """Update an existing display by id + + Parameters + ---------- + + obj: + The object with which to update the display + display_id: keyword-only + The id of the display to update + + See Also + -------- + + :func:`display` + """ + sentinel = object() + display_id = kwargs.pop('display_id', sentinel) + if display_id is sentinel: + raise TypeError("update_display() missing 1 required keyword-only argument: 'display_id'") + kwargs['update'] = True + display(obj, display_id=display_id, **kwargs) + + +class DisplayHandle(object): + """A handle on an updatable display + + Call `.update(obj)` to display a new object. + + Call `.display(obj`) to add a new instance of this display, + and update existing instances. + + See Also + -------- + + :func:`display`, :func:`update_display` + + """ + + def __init__(self, display_id=None): + if display_id is None: + display_id = _new_id() + self.display_id = display_id + + def __repr__(self): + return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) + + def display(self, obj, **kwargs): + """Make a new display with my id, updating existing instances. + + Parameters + ---------- + + obj: + object to display + **kwargs: + additional keyword arguments passed to display + """ + display(obj, display_id=self.display_id, **kwargs) + + def update(self, obj, **kwargs): + """Update existing displays with my id + + Parameters + ---------- + + obj: + object to display + **kwargs: + additional keyword arguments passed to update_display + """ + update_display(obj, display_id=self.display_id, **kwargs) + + def display_pretty(*objs, **kwargs): """Display the pretty (default) representation of an object. @@ -664,8 +664,8 @@ class TextDisplayObject(DisplayObject): class Pretty(TextDisplayObject): - def _repr_pretty_(self, pp, cycle): - return pp.text(self.data) + def _repr_pretty_(self, pp, cycle): + return pp.text(self.data) class HTML(TextDisplayObject): @@ -703,7 +703,7 @@ class Latex(TextDisplayObject): class SVG(DisplayObject): - _read_flags = 'rb' + _read_flags = 'rb' # wrap data in a property, which extracts the <svg> tag, discarding # document headers _data = None @@ -735,68 +735,68 @@ class SVG(DisplayObject): def _repr_svg_(self): return self.data -class ProgressBar(DisplayObject): - """Progressbar supports displaying a progressbar like element - """ - def __init__(self, total): - """Creates a new progressbar - - Parameters - ---------- - total : int - maximum size of the progressbar - """ - self.total = total - self._progress = 0 - self.html_width = '60ex' - self.text_width = 60 - self._display_id = hexlify(os.urandom(8)).decode('ascii') - - def __repr__(self): - fraction = self.progress / self.total - filled = '=' * int(fraction * self.text_width) - rest = ' ' * (self.text_width - len(filled)) - return '[{}{}] {}/{}'.format( - filled, rest, - self.progress, self.total, - ) - - def _repr_html_(self): - return "<progress style='width:{}' max='{}' value='{}'></progress>".format( - self.html_width, self.total, self.progress) - - def display(self): - display(self, display_id=self._display_id) - - def update(self): - display(self, display_id=self._display_id, update=True) - - @property - def progress(self): - return self._progress - - @progress.setter - def progress(self, value): - self._progress = value - self.update() - - def __iter__(self): - self.display() - self._progress = -1 # First iteration is 0 - return self - - def __next__(self): - """Returns current value and increments display by one.""" - self.progress += 1 - if self.progress < self.total: - return self.progress - else: - raise StopIteration() - - def next(self): - """Python 2 compatibility""" - return self.__next__() - +class ProgressBar(DisplayObject): + """Progressbar supports displaying a progressbar like element + """ + def __init__(self, total): + """Creates a new progressbar + + Parameters + ---------- + total : int + maximum size of the progressbar + """ + self.total = total + self._progress = 0 + self.html_width = '60ex' + self.text_width = 60 + self._display_id = hexlify(os.urandom(8)).decode('ascii') + + def __repr__(self): + fraction = self.progress / self.total + filled = '=' * int(fraction * self.text_width) + rest = ' ' * (self.text_width - len(filled)) + return '[{}{}] {}/{}'.format( + filled, rest, + self.progress, self.total, + ) + + def _repr_html_(self): + return "<progress style='width:{}' max='{}' value='{}'></progress>".format( + self.html_width, self.total, self.progress) + + def display(self): + display(self, display_id=self._display_id) + + def update(self): + display(self, display_id=self._display_id, update=True) + + @property + def progress(self): + return self._progress + + @progress.setter + def progress(self, value): + self._progress = value + self.update() + + def __iter__(self): + self.display() + self._progress = -1 # First iteration is 0 + return self + + def __next__(self): + """Returns current value and increments display by one.""" + self.progress += 1 + if self.progress < self.total: + return self.progress + else: + raise StopIteration() + + def next(self): + """Python 2 compatibility""" + return self.__next__() + class JSON(DisplayObject): """JSON expects a JSON-able dict or list @@ -1012,7 +1012,7 @@ class Image(DisplayObject): if ext is not None: if ext == u'jpg' or ext == u'jpeg': format = self._FMT_JPEG - elif ext == u'png': + elif ext == u'png': format = self._FMT_PNG else: format = ext.lower() diff --git a/contrib/python/ipython/py2/IPython/core/displayhook.py b/contrib/python/ipython/py2/IPython/core/displayhook.py index cce7c83d16..50aaa7a50c 100644 --- a/contrib/python/ipython/py2/IPython/core/displayhook.py +++ b/contrib/python/ipython/py2/IPython/core/displayhook.py @@ -45,7 +45,7 @@ class DisplayHook(Configurable): self.do_full_cache = 0 cache_size = 0 warn('caching was disabled (min value for cache size is %s).' % - cache_size_min,stacklevel=3) + cache_size_min,stacklevel=3) else: self.do_full_cache = 1 @@ -293,17 +293,17 @@ class DisplayHook(Configurable): # IronPython blocks here forever if sys.platform != "cli": gc.collect() - - -class CapturingDisplayHook(object): - def __init__(self, shell, outputs=None): - self.shell = shell - if outputs is None: - outputs = [] - self.outputs = outputs - - def __call__(self, result=None): - if result is None: - return - format_dict, md_dict = self.shell.display_formatter.format(result) - self.outputs.append({ 'data': format_dict, 'metadata': md_dict }) + + +class CapturingDisplayHook(object): + def __init__(self, shell, outputs=None): + self.shell = shell + if outputs is None: + outputs = [] + self.outputs = outputs + + def __call__(self, result=None): + if result is None: + return + format_dict, md_dict = self.shell.display_formatter.format(result) + self.outputs.append({ 'data': format_dict, 'metadata': md_dict }) diff --git a/contrib/python/ipython/py2/IPython/core/displaypub.py b/contrib/python/ipython/py2/IPython/core/displaypub.py index 82a859ae15..cb60efb52a 100644 --- a/contrib/python/ipython/py2/IPython/core/displaypub.py +++ b/contrib/python/ipython/py2/IPython/core/displaypub.py @@ -53,8 +53,8 @@ class DisplayPublisher(Configurable): if not isinstance(metadata, dict): raise TypeError('metadata must be a dict, got: %r' % data) - # use * to indicate transient, update are keyword-only - def publish(self, data, metadata=None, source=None, **kwargs): + # use * to indicate transient, update are keyword-only + def publish(self, data, metadata=None, source=None, **kwargs): """Publish data and metadata to all frontends. See the ``display_data`` message in the messaging documentation for @@ -90,21 +90,21 @@ class DisplayPublisher(Configurable): the data itself. source : str, deprecated Unused. - transient: dict, keyword-only - A dictionary for transient data. - Data in this dictionary should not be persisted as part of saving this output. - Examples include 'display_id'. - update: bool, keyword-only, default: False - If True, only update existing outputs with the same display_id, - rather than creating a new output. + transient: dict, keyword-only + A dictionary for transient data. + Data in this dictionary should not be persisted as part of saving this output. + Examples include 'display_id'. + update: bool, keyword-only, default: False + If True, only update existing outputs with the same display_id, + rather than creating a new output. """ - # These are kwargs only on Python 3, not used there. - # For consistency and avoid code divergence we leave them here to - # simplify potential backport - transient = kwargs.pop('transient', None) - update = kwargs.pop('update', False) - + # These are kwargs only on Python 3, not used there. + # For consistency and avoid code divergence we leave them here to + # simplify potential backport + transient = kwargs.pop('transient', None) + update = kwargs.pop('update', False) + # The default is to simply write the plain text data using sys.stdout. if 'text/plain' in data: print(data['text/plain']) @@ -121,19 +121,19 @@ class CapturingDisplayPublisher(DisplayPublisher): """A DisplayPublisher that stores""" outputs = List() - def publish(self, data, metadata=None, source=None, **kwargs): - - # These are kwargs only on Python 3, not used there. - # For consistency and avoid code divergence we leave them here to - # simplify potential backport - transient = kwargs.pop('transient', None) - update = kwargs.pop('update', False) - - self.outputs.append({'data':data, 'metadata':metadata, - 'transient':transient, 'update':update}) - + def publish(self, data, metadata=None, source=None, **kwargs): + + # These are kwargs only on Python 3, not used there. + # For consistency and avoid code divergence we leave them here to + # simplify potential backport + transient = kwargs.pop('transient', None) + update = kwargs.pop('update', False) + + self.outputs.append({'data':data, 'metadata':metadata, + 'transient':transient, 'update':update}) + def clear_output(self, wait=False): super(CapturingDisplayPublisher, self).clear_output(wait) - + # empty the list, *do not* reassign a new list - self.outputs.clear() + self.outputs.clear() diff --git a/contrib/python/ipython/py2/IPython/core/excolors.py b/contrib/python/ipython/py2/IPython/core/excolors.py index 487bde18c8..ed28b9564b 100644 --- a/contrib/python/ipython/py2/IPython/core/excolors.py +++ b/contrib/python/ipython/py2/IPython/core/excolors.py @@ -3,7 +3,7 @@ Color schemes for exception handling code in IPython. """ -import os +import os import warnings #***************************************************************************** @@ -156,12 +156,12 @@ def exception_colors(): 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')) + # 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 @@ -172,8 +172,8 @@ class Deprec(object): def __getattr__(self, name): val = getattr(self.wrapped, name) - warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0", - DeprecationWarning, stacklevel=2) + warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0", + DeprecationWarning, stacklevel=2) # using getattr after warnings break ipydoctest in weird way for 3.5 return val diff --git a/contrib/python/ipython/py2/IPython/core/formatters.py b/contrib/python/ipython/py2/IPython/core/formatters.py index d990619f27..964c0e4791 100644 --- a/contrib/python/ipython/py2/IPython/core/formatters.py +++ b/contrib/python/ipython/py2/IPython/core/formatters.py @@ -53,17 +53,17 @@ class DisplayFormatter(Configurable): formatter.enabled = True else: formatter.enabled = False - + ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') @default('ipython_display_formatter') def _default_formatter(self): return IPythonDisplayFormatter(parent=self) - - mimebundle_formatter = ForwardDeclaredInstance('FormatterABC') - @default('mimebundle_formatter') - def _default_mime_formatter(self): - return MimeBundleFormatter(parent=self) - + + mimebundle_formatter = ForwardDeclaredInstance('FormatterABC') + @default('mimebundle_formatter') + def _default_mime_formatter(self): + return MimeBundleFormatter(parent=self) + # A dict of formatter whose keys are format types (MIME types) and whose # values are subclasses of BaseFormatter. formatters = Dict() @@ -93,7 +93,7 @@ class DisplayFormatter(Configurable): By default all format types will be computed. - The following MIME types are usually implemented: + The following MIME types are usually implemented: * text/plain * text/html @@ -110,15 +110,15 @@ class DisplayFormatter(Configurable): ---------- obj : object The Python object whose format data will be computed. - include : list, tuple or set; optional + include : list, tuple or set; optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. - exclude : list, tuple or set; optional + exclude : list, tuple or set; optional A list of format type string (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument. - Mimetypes present in exclude will take precedence over the ones in include + Mimetypes present in exclude will take precedence over the ones in include Returns ------- @@ -132,15 +132,15 @@ class DisplayFormatter(Configurable): metadata_dict is a dictionary of metadata about each mime-type output. Its keys will be a strict subset of the keys in format_dict. - - Notes - ----- - - If an object implement `_repr_mimebundle_` as well as various - `_repr_*_`, the data returned by `_repr_mimebundle_` will take - precedence and the corresponding `_repr_*_` for this mimetype will - not be called. - + + Notes + ----- + + If an object implement `_repr_mimebundle_` as well as various + `_repr_*_`, the data returned by `_repr_mimebundle_` will take + precedence and the corresponding `_repr_*_` for this mimetype will + not be called. + """ format_dict = {} md_dict = {} @@ -148,21 +148,21 @@ class DisplayFormatter(Configurable): if self.ipython_display_formatter(obj): # object handled itself, don't proceed return {}, {} - - format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude) - - if format_dict or md_dict: - if include: - format_dict = {k:v for k,v in format_dict.items() if k in include} - md_dict = {k:v for k,v in md_dict.items() if k in include} - if exclude: - format_dict = {k:v for k,v in format_dict.items() if k not in exclude} - md_dict = {k:v for k,v in md_dict.items() if k not in exclude} - + + format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude) + + if format_dict or md_dict: + if include: + format_dict = {k:v for k,v in format_dict.items() if k in include} + md_dict = {k:v for k,v in md_dict.items() if k in include} + if exclude: + format_dict = {k:v for k,v in format_dict.items() if k not in exclude} + md_dict = {k:v for k,v in md_dict.items() if k not in exclude} + for format_type, formatter in self.formatters.items(): - if format_type in format_dict: - # already got it from mimebundle, don't render again - continue + if format_type in format_dict: + # already got it from mimebundle, don't render again + continue if include and format_type not in include: continue if exclude and format_type in exclude: @@ -217,7 +217,7 @@ def catch_format_error(method, self, *args, **kwargs): r = method(self, *args, **kwargs) except NotImplementedError: # don't warn on NotImplementedErrors - return self._check_return(None, args[0]) + return self._check_return(None, args[0]) except Exception: exc_info = sys.exc_info() ip = get_ipython() @@ -225,7 +225,7 @@ def catch_format_error(method, self, *args, **kwargs): ip.showtraceback(exc_info) else: traceback.print_exception(*exc_info) - return self._check_return(None, args[0]) + return self._check_return(None, args[0]) return self._check_return(r, args[0]) @@ -876,7 +876,7 @@ class PDFFormatter(BaseFormatter): _return_type = (bytes, unicode_type) class IPythonDisplayFormatter(BaseFormatter): - """An escape-hatch Formatter for objects that know how to display themselves. + """An escape-hatch Formatter for objects that know how to display themselves. To define the callables that compute the representation of your objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` @@ -886,13 +886,13 @@ class IPythonDisplayFormatter(BaseFormatter): This display formatter has highest priority. If it fires, no other display formatter will be called. - - Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types - without registering a new Formatter. - - IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types, - so `_ipython_display_` should only be used for objects that require unusual - display patterns, such as multiple display calls. + + Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types + without registering a new Formatter. + + IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types, + so `_ipython_display_` should only be used for objects that require unusual + display patterns, such as multiple display calls. """ print_method = ObjectName('_ipython_display_') _return_type = (type(None), bool) @@ -916,63 +916,63 @@ class IPythonDisplayFormatter(BaseFormatter): return True -class MimeBundleFormatter(BaseFormatter): - """A Formatter for arbitrary mime-types. - - Unlike other `_repr_<mimetype>_` methods, - `_repr_mimebundle_` should return mime-bundle data, - either the mime-keyed `data` dictionary or the tuple `(data, metadata)`. - Any mime-type is valid. - - To define the callables that compute the mime-bundle representation of your - objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type` - or :meth:`for_type_by_name` methods to register functions that handle - this. - - .. versionadded:: 6.1 - """ - print_method = ObjectName('_repr_mimebundle_') - _return_type = dict - - def _check_return(self, r, obj): - r = super(MimeBundleFormatter, self)._check_return(r, obj) - # always return (data, metadata): - if r is None: - return {}, {} - if not isinstance(r, tuple): - return r, {} - return r - - @catch_format_error - def __call__(self, obj, include=None, exclude=None): - """Compute the format for an object. - - Identical to parent's method but we pass extra parameters to the method. - - Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in - particular `include` and `exclude`. - """ - if self.enabled: - # lookup registered printer - try: - printer = self.lookup(obj) - except KeyError: - pass - else: - return printer(obj) - # Finally look for special method names - method = get_real_method(obj, self.print_method) - - if method is not None: - d = {} - d['include'] = include - d['exclude'] = exclude - return method(**d) - return None - else: - return None - - +class MimeBundleFormatter(BaseFormatter): + """A Formatter for arbitrary mime-types. + + Unlike other `_repr_<mimetype>_` methods, + `_repr_mimebundle_` should return mime-bundle data, + either the mime-keyed `data` dictionary or the tuple `(data, metadata)`. + Any mime-type is valid. + + To define the callables that compute the mime-bundle representation of your + objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type` + or :meth:`for_type_by_name` methods to register functions that handle + this. + + .. versionadded:: 6.1 + """ + print_method = ObjectName('_repr_mimebundle_') + _return_type = dict + + def _check_return(self, r, obj): + r = super(MimeBundleFormatter, self)._check_return(r, obj) + # always return (data, metadata): + if r is None: + return {}, {} + if not isinstance(r, tuple): + return r, {} + return r + + @catch_format_error + def __call__(self, obj, include=None, exclude=None): + """Compute the format for an object. + + Identical to parent's method but we pass extra parameters to the method. + + Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in + particular `include` and `exclude`. + """ + if self.enabled: + # lookup registered printer + try: + printer = self.lookup(obj) + except KeyError: + pass + else: + return printer(obj) + # Finally look for special method names + method = get_real_method(obj, self.print_method) + + if method is not None: + d = {} + d['include'] = include + d['exclude'] = exclude + return method(**d) + return None + else: + return None + + FormatterABC.register(BaseFormatter) FormatterABC.register(PlainTextFormatter) FormatterABC.register(HTMLFormatter) @@ -985,7 +985,7 @@ FormatterABC.register(LatexFormatter) FormatterABC.register(JSONFormatter) FormatterABC.register(JavascriptFormatter) FormatterABC.register(IPythonDisplayFormatter) -FormatterABC.register(MimeBundleFormatter) +FormatterABC.register(MimeBundleFormatter) def format_display_data(obj, include=None, exclude=None): diff --git a/contrib/python/ipython/py2/IPython/core/history.py b/contrib/python/ipython/py2/IPython/core/history.py index 2e7fdbc845..894f927f7a 100644 --- a/contrib/python/ipython/py2/IPython/core/history.py +++ b/contrib/python/ipython/py2/IPython/core/history.py @@ -21,7 +21,7 @@ import threading from traitlets.config.configurable import LoggingConfigurable from decorator import decorator from IPython.utils.decorators import undoc -from IPython.paths import locate_profile +from IPython.paths import locate_profile from IPython.utils import py3compat from traitlets import ( Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError, @@ -301,8 +301,8 @@ class HistoryAccessor(HistoryAccessorBase): cur = self.db.execute("SELECT session, line, %s FROM %s " %\ (toget, sqlfrom) + sql, params) if output: # Regroup into 3-tuples, and parse JSON - return ((ses, lin, (py3compat.cast_unicode_py2(inp), py3compat.cast_unicode_py2(out))) - for ses, lin, inp, out in cur) + return ((ses, lin, (py3compat.cast_unicode_py2(inp), py3compat.cast_unicode_py2(out))) + for ses, lin, inp, out in cur) return cur @needs_sqlite diff --git a/contrib/python/ipython/py2/IPython/core/hooks.py b/contrib/python/ipython/py2/IPython/core/hooks.py index e6fc84087f..482a44a79e 100644 --- a/contrib/python/ipython/py2/IPython/core/hooks.py +++ b/contrib/python/ipython/py2/IPython/core/hooks.py @@ -99,7 +99,7 @@ def fix_error_editor(self,filename,linenum,column,msg): 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: +the mailing list ipython-dev@python.org , or on the GitHub Issue tracker: https://github.com/ipython/ipython/issues/9649 """, UserWarning) def vim_quickfix_file(): diff --git a/contrib/python/ipython/py2/IPython/core/inputtransformer.py b/contrib/python/ipython/py2/IPython/core/inputtransformer.py index 3ba49b951d..b321e3c1ba 100644 --- a/contrib/python/ipython/py2/IPython/core/inputtransformer.py +++ b/contrib/python/ipython/py2/IPython/core/inputtransformer.py @@ -126,19 +126,19 @@ class TokenInputTransformer(InputTransformer): """ def __init__(self, func): self.func = func - self.buf = [] + self.buf = [] self.reset_tokenizer() - + def reset_tokenizer(self): - it = iter(self.buf) - nxt = it.__next__ if PY3 else it.next - self.tokenizer = generate_tokens(nxt) - + it = iter(self.buf) + nxt = it.__next__ if PY3 else it.next + self.tokenizer = generate_tokens(nxt) + def push(self, line): - self.buf.append(line + '\n') - if all(l.isspace() for l in self.buf): + self.buf.append(line + '\n') + if all(l.isspace() for l in self.buf): return self.reset() - + tokens = [] stop_at_NL = False try: @@ -158,13 +158,13 @@ class TokenInputTransformer(InputTransformer): return self.output(tokens) def output(self, tokens): - self.buf[:] = [] + self.buf[:] = [] self.reset_tokenizer() return untokenize(self.func(tokens)).rstrip('\n') def reset(self): - l = ''.join(self.buf) - self.buf[:] = [] + l = ''.join(self.buf) + self.buf[:] = [] self.reset_tokenizer() if l: return l.rstrip('\n') diff --git a/contrib/python/ipython/py2/IPython/core/interactiveshell.py b/contrib/python/ipython/py2/IPython/core/interactiveshell.py index ad8824b606..52d80fceeb 100644 --- a/contrib/python/ipython/py2/IPython/core/interactiveshell.py +++ b/contrib/python/ipython/py2/IPython/core/interactiveshell.py @@ -58,7 +58,7 @@ 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.display import display +from IPython.display import display from IPython.utils import PyColorize from IPython.utils import io from IPython.utils import py3compat @@ -637,7 +637,7 @@ class InteractiveShell(SingletonConfigurable): # removing on exit or representing the existence of more than one # IPython at a time. builtin_mod.__dict__['__IPYTHON__'] = True - builtin_mod.__dict__['display'] = display + builtin_mod.__dict__['display'] = display self.builtin_trap = BuiltinTrap(shell=self) @@ -2064,7 +2064,7 @@ class InteractiveShell(SingletonConfigurable): etpl = "Line magic function `%%%s` not found%s." extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' 'did you mean that instead?)' % magic_name ) - raise UsageError(etpl % (magic_name, extra)) + raise UsageError(etpl % (magic_name, extra)) else: # Note: this is the distance in the stack to the user's frame. # This will need to be updated if the internal calling logic gets @@ -2101,7 +2101,7 @@ class InteractiveShell(SingletonConfigurable): etpl = "Cell magic `%%{0}` not found{1}." extra = '' if lm is None else (' (But line magic `%{0}` exists, ' 'did you mean that instead?)'.format(magic_name)) - raise UsageError(etpl.format(magic_name, extra)) + raise UsageError(etpl.format(magic_name, extra)) elif cell == '': message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) if self.find_line_magic(magic_name) is not None: @@ -2537,12 +2537,12 @@ class InteractiveShell(SingletonConfigurable): """generator for sequence of code blocks to run""" if fname.endswith('.ipynb'): from nbformat import read - nb = read(fname, as_version=4) - if not nb.cells: - return - for cell in nb.cells: - if cell.cell_type == 'code': - yield cell.source + nb = read(fname, as_version=4) + if not nb.cells: + return + for cell in nb.cells: + if cell.cell_type == 'code': + yield cell.source else: with open(fname) as f: yield f.read() @@ -2626,8 +2626,8 @@ class InteractiveShell(SingletonConfigurable): result.execution_count = self.execution_count def error_before_exec(value): - if store_history: - self.execution_count += 1 + if store_history: + self.execution_count += 1 result.error_before_exec = value self.last_execution_succeeded = False return result @@ -2900,32 +2900,32 @@ class InteractiveShell(SingletonConfigurable): # For backwards compatibility runcode = run_code - def check_complete(self, code): - """Return whether a block of code is ready to execute, or should be continued - - Parameters - ---------- - source : string - Python input code, which can be multiline. - - Returns - ------- - status : str - One of 'complete', 'incomplete', or 'invalid' if source is not a - prefix of valid code. - indent : str - When status is 'incomplete', this is some whitespace to insert on - the next line of the prompt. - """ - status, nspaces = self.input_splitter.check_complete(code) - return status, ' ' * (nspaces or 0) - + def check_complete(self, code): + """Return whether a block of code is ready to execute, or should be continued + + Parameters + ---------- + source : string + Python input code, which can be multiline. + + Returns + ------- + status : str + One of 'complete', 'incomplete', or 'invalid' if source is not a + prefix of valid code. + indent : str + When status is 'incomplete', this is some whitespace to insert on + the next line of the prompt. + """ + status, nspaces = self.input_splitter.check_complete(code) + return status, ' ' * (nspaces or 0) + #------------------------------------------------------------------------- # Things related to GUI support and pylab #------------------------------------------------------------------------- - active_eventloop = None - + active_eventloop = None + def enable_gui(self, gui=None): raise NotImplementedError('Implement enable_gui in a subclass') diff --git a/contrib/python/ipython/py2/IPython/core/magics/basic.py b/contrib/python/ipython/py2/IPython/core/magics/basic.py index ca69e2e698..304bf4228c 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/basic.py +++ b/contrib/python/ipython/py2/IPython/core/magics/basic.py @@ -3,7 +3,7 @@ from __future__ import print_function from __future__ import absolute_import -import argparse +import argparse import io import sys from pprint import pformat @@ -288,14 +288,14 @@ Currently the magic system has the following functions:""", @line_magic def profile(self, parameter_s=''): - """DEPRECATED since IPython 2.0. - - Raise `UsageError`. To profile code use the :magic:`prun` magic. - + """DEPRECATED since IPython 2.0. + Raise `UsageError`. To profile code use the :magic:`prun` magic. + + See Also -------- - prun : run code using the Python profiler (:magic:`prun`) + prun : run code using the Python profiler (:magic:`prun`) """ warn("%profile is now deprecated. Please use get_ipython().profile instead.") from IPython.core.application import BaseIPythonApplication @@ -551,7 +551,7 @@ Currently the magic system has the following functions:""", @magic_arguments.magic_arguments() @magic_arguments.argument( '-e', '--export', action='store_true', default=False, - help=argparse.SUPPRESS + help=argparse.SUPPRESS ) @magic_arguments.argument( 'filename', type=unicode_type, @@ -562,24 +562,24 @@ Currently the magic system has the following functions:""", """Export and convert IPython notebooks. This function can export the current IPython history to a notebook file. - For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". - - The -e or --export flag is deprecated in IPython 5.2, and will be - removed in the future. + For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". + + The -e or --export flag is deprecated in IPython 5.2, and will be + removed in the future. """ args = magic_arguments.parse_argstring(self.notebook, s) from nbformat import write, v4 - - cells = [] - hist = list(self.shell.history_manager.get_range()) - if(len(hist)<=1): - raise ValueError('History is empty, cannot export') - for session, execution_count, source in hist[:-1]: - cells.append(v4.new_code_cell( - execution_count=execution_count, - source=source - )) - nb = v4.new_notebook(cells=cells) - with io.open(args.filename, 'w', encoding='utf-8') as f: - write(nb, f, version=4) + + cells = [] + hist = list(self.shell.history_manager.get_range()) + if(len(hist)<=1): + raise ValueError('History is empty, cannot export') + for session, execution_count, source in hist[:-1]: + cells.append(v4.new_code_cell( + execution_count=execution_count, + source=source + )) + nb = v4.new_notebook(cells=cells) + with io.open(args.filename, 'w', encoding='utf-8') as f: + write(nb, f, version=4) diff --git a/contrib/python/ipython/py2/IPython/core/magics/execution.py b/contrib/python/ipython/py2/IPython/core/magics/execution.py index 3734b0cdae..73f7581cb6 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/execution.py +++ b/contrib/python/ipython/py2/IPython/core/magics/execution.py @@ -437,7 +437,7 @@ python-profiler package from non-free.""") def _debug_exec(self, code, breakpoint): if breakpoint: - (filename, bp_line) = breakpoint.rsplit(':', 1) + (filename, bp_line) = breakpoint.rsplit(':', 1) bp_line = int(bp_line) else: (filename, bp_line) = (None, None) @@ -806,17 +806,17 @@ python-profiler package from non-free.""") 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'): - del deb.curframe - + # 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'): + del deb.curframe + # reset Breakpoint state, which is moronically kept # in a class bdb.Breakpoint.next = 1 bdb.Breakpoint.bplist = {} bdb.Breakpoint.bpbynumber = [None] - deb.clear_all_breaks() + deb.clear_all_breaks() if bp_line is not None: # Set an initial breakpoint to stop execution maxtries = 10 @@ -1013,13 +1013,13 @@ python-profiler package from non-free.""") ast_setup = self.shell.transform_ast(ast_setup) ast_stmt = self.shell.transform_ast(ast_stmt) - # Check that these compile to valid Python code *outside* the timer func - # Invalid code may become valid when put inside the function & loop, - # which messes up error messages. - # https://github.com/ipython/ipython/issues/10636 - self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec") - self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec") - + # Check that these compile to valid Python code *outside* the timer func + # Invalid code may become valid when put inside the function & loop, + # which messes up error messages. + # https://github.com/ipython/ipython/issues/10636 + self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec") + self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec") + # This codestring is taken from timeit.template - we fill it in as an # AST, so that we can apply our AST transformations to the user code # without affecting the timing code. diff --git a/contrib/python/ipython/py2/IPython/core/magics/script.py b/contrib/python/ipython/py2/IPython/core/magics/script.py index 3fbddc38a8..22e6c46579 100644 --- a/contrib/python/ipython/py2/IPython/core/magics/script.py +++ b/contrib/python/ipython/py2/IPython/core/magics/script.py @@ -246,8 +246,8 @@ class ScriptMagics(Magics): def kill_bg_processes(self): """Kill all BG processes which are still running.""" - if not self.bg_processes: - return + if not self.bg_processes: + return for p in self.bg_processes: if p.poll() is None: try: @@ -255,9 +255,9 @@ class ScriptMagics(Magics): except: pass time.sleep(0.1) - self._gc_bg_processes() - if not self.bg_processes: - return + self._gc_bg_processes() + if not self.bg_processes: + return for p in self.bg_processes: if p.poll() is None: try: @@ -265,9 +265,9 @@ class ScriptMagics(Magics): except: pass time.sleep(0.1) - self._gc_bg_processes() - if not self.bg_processes: - return + self._gc_bg_processes() + if not self.bg_processes: + return for p in self.bg_processes: if p.poll() is None: try: diff --git a/contrib/python/ipython/py2/IPython/core/oinspect.py b/contrib/python/ipython/py2/IPython/core/oinspect.py index 55a4efe8c0..0360a9c98f 100644 --- a/contrib/python/ipython/py2/IPython/core/oinspect.py +++ b/contrib/python/ipython/py2/IPython/core/oinspect.py @@ -651,7 +651,7 @@ class Inspector(Colorable): # Functions, methods, classes append_field(_mime, 'Signature', 'definition', code_formatter) append_field(_mime, 'Init signature', 'init_definition', code_formatter) - if detail_level > 0 and info['source']: + if detail_level > 0 and info['source']: append_field(_mime, 'Source', 'source', code_formatter) else: append_field(_mime, 'Docstring', 'docstring', formatter) @@ -662,9 +662,9 @@ class Inspector(Colorable): else: # General Python objects - append_field(_mime, 'Signature', 'definition', code_formatter) - append_field(_mime, 'Call signature', 'call_def', code_formatter) - + append_field(_mime, 'Signature', 'definition', code_formatter) + append_field(_mime, 'Call signature', 'call_def', code_formatter) + append_field(_mime, 'Type', 'type_name') # Base class for old-style instances @@ -678,8 +678,8 @@ class Inspector(Colorable): append_field(_mime, 'Namespace', 'namespace') append_field(_mime, 'Length', 'length') - append_field(_mime, 'File', 'file') - + append_field(_mime, 'File', 'file') + # Source or docstring, depending on detail level and whether # source found. if detail_level > 0: @@ -690,7 +690,7 @@ class Inspector(Colorable): 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) diff --git a/contrib/python/ipython/py2/IPython/core/pylabtools.py b/contrib/python/ipython/py2/IPython/core/pylabtools.py index a1932d8c48..63c38b4386 100644 --- a/contrib/python/ipython/py2/IPython/core/pylabtools.py +++ b/contrib/python/ipython/py2/IPython/core/pylabtools.py @@ -19,18 +19,18 @@ backends = {'tk': 'TkAgg', 'wx': 'WXAgg', 'qt4': 'Qt4Agg', 'qt5': 'Qt5Agg', - 'qt': 'Qt5Agg', + 'qt': 'Qt5Agg', 'osx': 'MacOSX', 'nbagg': 'nbAgg', 'notebook': 'nbAgg', - 'agg': 'agg', - 'svg': 'svg', - 'pdf': 'pdf', - 'ps': 'ps', - 'inline': 'module://ipykernel.pylab.backend_inline', - 'ipympl': 'module://ipympl.backend_nbagg', - 'widget': 'module://ipympl.backend_nbagg', - } + 'agg': 'agg', + 'svg': 'svg', + 'pdf': 'pdf', + 'ps': 'ps', + 'inline': 'module://ipykernel.pylab.backend_inline', + 'ipympl': 'module://ipympl.backend_nbagg', + 'widget': 'module://ipympl.backend_nbagg', + } # We also need a reverse backends2guis mapping that will properly choose which # GUI support to activate based on the desired matplotlib backend. For the @@ -45,13 +45,13 @@ backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk' backend2gui['GTK3Cairo'] = 'gtk3' backend2gui['WX'] = 'wx' backend2gui['CocoaAgg'] = 'osx' -# And some backends that don't need GUI integration -del backend2gui['nbAgg'] -del backend2gui['agg'] -del backend2gui['svg'] -del backend2gui['pdf'] -del backend2gui['ps'] -del backend2gui['module://ipykernel.pylab.backend_inline'] +# And some backends that don't need GUI integration +del backend2gui['nbAgg'] +del backend2gui['agg'] +del backend2gui['svg'] +del backend2gui['pdf'] +del backend2gui['ps'] +del backend2gui['module://ipykernel.pylab.backend_inline'] #----------------------------------------------------------------------------- # Matplotlib utilities @@ -111,7 +111,7 @@ def print_figure(fig, fmt='png', bbox_inches='tight', **kwargs): if not fig.axes and not fig.lines: return - dpi = fig.dpi + dpi = fig.dpi if fmt == 'retina': dpi = dpi * 2 fmt = 'png' @@ -171,7 +171,7 @@ def mpl_runner(safe_execfile): properly handle interactive rendering.""" import matplotlib - import matplotlib.pyplot as plt + import matplotlib.pyplot as plt #print '*** Matplotlib runner ***' # dbg # turn off rendering until end of script @@ -180,18 +180,18 @@ def mpl_runner(safe_execfile): safe_execfile(fname,*where,**kw) matplotlib.interactive(is_interactive) # make rendering call now, if the user tried to do it - if plt.draw_if_interactive.called: - plt.draw() - plt.draw_if_interactive.called = False - - # re-draw everything that is stale - try: - da = plt.draw_all - except AttributeError: - pass - else: - da() - + if plt.draw_if_interactive.called: + plt.draw() + plt.draw_if_interactive.called = False + + # re-draw everything that is stale + try: + da = plt.draw_all + except AttributeError: + pass + else: + da() + return mpl_execfile @@ -231,8 +231,8 @@ def select_figure_formats(shell, formats, **kwargs): formats = set(formats) [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ] - mplbackend = matplotlib.get_backend().lower() - if mplbackend == 'nbagg' or mplbackend == 'module://ipympl.backend_nbagg': + mplbackend = matplotlib.get_backend().lower() + if mplbackend == 'nbagg' or mplbackend == 'module://ipympl.backend_nbagg': formatter = shell.display_formatter.ipython_display_formatter formatter.for_type(Figure, _reshow_nbagg_figure) @@ -316,12 +316,12 @@ def activate_matplotlib(backend): # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made - import matplotlib.pyplot as plt + import matplotlib.pyplot as plt - plt.show._needmain = False + plt.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. - plt.draw_if_interactive = flag_calls(plt.draw_if_interactive) + plt.draw_if_interactive = flag_calls(plt.draw_if_interactive) def import_pylab(user_ns, import_all=True): diff --git a/contrib/python/ipython/py2/IPython/core/release.py b/contrib/python/ipython/py2/IPython/core/release.py index 94dea1073b..494e7e41ee 100644 --- a/contrib/python/ipython/py2/IPython/core/release.py +++ b/contrib/python/ipython/py2/IPython/core/release.py @@ -101,9 +101,9 @@ authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'), author = 'The IPython Development Team' -author_email = 'ipython-dev@python.org' +author_email = 'ipython-dev@python.org' -url = 'https://ipython.org' +url = 'https://ipython.org' platforms = ['Linux','Mac OSX','Windows'] diff --git a/contrib/python/ipython/py2/IPython/core/shellapp.py b/contrib/python/ipython/py2/IPython/core/shellapp.py index 213648246e..43b900ea5a 100644 --- a/contrib/python/ipython/py2/IPython/core/shellapp.py +++ b/contrib/python/ipython/py2/IPython/core/shellapp.py @@ -11,14 +11,14 @@ from __future__ import absolute_import from __future__ import print_function import glob -from itertools import chain +from itertools import chain import os import sys from traitlets.config.application import boolean_flag from traitlets.config.configurable import Configurable from traitlets.config.loader import Config -from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS +from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS from IPython.core import pylabtools from IPython.utils import py3compat from IPython.utils.contexts import preserve_keys @@ -333,9 +333,9 @@ class InteractiveShellApp(Configurable): def _run_startup_files(self): """Run files from profile startup directory""" - startup_dirs = [self.profile_dir.startup_dir] + [ - os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS) - ] + startup_dirs = [self.profile_dir.startup_dir] + [ + 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 \ @@ -347,9 +347,9 @@ class InteractiveShellApp(Configurable): except: self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup) self.shell.showtraceback() - for startup_dir in startup_dirs[::-1]: - startup_files += glob.glob(os.path.join(startup_dir, '*.py')) - startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) + for startup_dir in startup_dirs[::-1]: + startup_files += glob.glob(os.path.join(startup_dir, '*.py')) + startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) if not startup_files: return diff --git a/contrib/python/ipython/py2/IPython/core/ultratb.py b/contrib/python/ipython/py2/IPython/core/ultratb.py index a855145825..2977e9109b 100644 --- a/contrib/python/ipython/py2/IPython/core/ultratb.py +++ b/contrib/python/ipython/py2/IPython/core/ultratb.py @@ -438,7 +438,7 @@ def is_recursion_error(etype, value, records): # by stack frames in IPython itself. >500 frames probably indicates # a recursion error. return (etype is recursion_error_type) \ - and str("recursion") in str(value).lower() \ + and str("recursion") in str(value).lower() \ and len(records) > 500 def find_recursion(etype, value, records): @@ -1130,12 +1130,12 @@ class VerboseTB(TBTools): # problems, but it generates empty tracebacks for console errors # (5 blanks lines) where none should be returned. return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) - except UnicodeDecodeError: - # This can occur if a file's encoding magic comment is wrong. - # I can't see a way to recover without duplicating a bunch of code - # from the stdlib traceback module. --TK - error('\nUnicodeDecodeError while processing traceback.\n') - return None + except UnicodeDecodeError: + # This can occur if a file's encoding magic comment is wrong. + # I can't see a way to recover without duplicating a bunch of code + # from the stdlib traceback module. --TK + error('\nUnicodeDecodeError while processing traceback.\n') + return None except: # FIXME: I've been getting many crash reports from python 2.3 # users, traceable to inspect.py. If I can find a small test-case @@ -1227,7 +1227,7 @@ class VerboseTB(TBTools): if force or self.call_pdb: if self.pdb is None: - self.pdb = self.debugger_cls() + self.pdb = self.debugger_cls() # the system displayhook may have changed, restore the original # for pdb display_trap = DisplayTrap(hook=sys.__displayhook__) diff --git a/contrib/python/ipython/py2/IPython/core/usage.py b/contrib/python/ipython/py2/IPython/core/usage.py index c4d3c16eca..0ad963646d 100644 --- a/contrib/python/ipython/py2/IPython/core/usage.py +++ b/contrib/python/ipython/py2/IPython/core/usage.py @@ -67,9 +67,9 @@ interactive_usage = """ IPython -- An enhanced Interactive Python ========================================= -IPython offers a fully compatible replacement for the standard Python -interpreter, with convenient shell features, special commands, command -history mechanism and output results caching. +IPython offers a fully compatible replacement for the standard Python +interpreter, with convenient shell features, special commands, command +history mechanism and output results caching. At your system command line, type 'ipython -h' to see the command line options available. This document only describes interactive features. @@ -77,8 +77,8 @@ options available. This document only describes interactive features. MAIN FEATURES ------------- -* Access to the standard Python help with object docstrings and the Python - manuals. Simply type 'help' (no quotes) to invoke it. +* Access to the standard Python help with object docstrings and the Python + manuals. Simply type 'help' (no quotes) to invoke it. * Magic commands: type %magic for information on the magic subsystem. @@ -86,12 +86,12 @@ MAIN FEATURES * Dynamic object information: - Typing ?word or word? prints detailed information about an object. Certain - long strings (code, etc.) get snipped in the center for brevity. + Typing ?word or word? prints detailed information about an object. Certain + long strings (code, etc.) get snipped in the center for brevity. Typing ??word or word?? gives access to the full information without - snipping long strings. Strings that are longer than the screen are printed - through the less pager. + snipping long strings. Strings that are longer than the screen are printed + through the less pager. The ?/?? system gives access to the full source code for any object (if available), shows function prototypes and other useful information. @@ -99,16 +99,16 @@ MAIN FEATURES If you just want to see an object's docstring, type '%pdoc object' (without quotes, and without % if you have automagic on). -* Tab completion in the local namespace: +* Tab completion in the local namespace: At any time, hitting tab will complete any available python commands or variable names, and show you a list of the possible completions if there's no unambiguous one. It will also complete filenames in the current directory. -* Search previous command history in multiple ways: +* Search previous command history in multiple ways: - - Start typing, and then use arrow keys up/down or (Ctrl-p/Ctrl-n) to search - through the history items that match what you've typed so far. + - Start typing, and then use arrow keys up/down or (Ctrl-p/Ctrl-n) to search + through the history items that match what you've typed so far. - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches your history for lines that match what you've typed so far, completing as @@ -120,7 +120,7 @@ MAIN FEATURES * Logging of input with the ability to save and restore a working session. -* System shell with !. Typing !ls will run 'ls' in the current directory. +* System shell with !. Typing !ls will run 'ls' in the current directory. * The reload command does a 'deep' reload of a module: changes made to the module since you imported will actually be available without having to exit. diff --git a/contrib/python/ipython/py2/IPython/extensions/autoreload.py b/contrib/python/ipython/py2/IPython/extensions/autoreload.py index d3e420574d..66f3f94ef1 100644 --- a/contrib/python/ipython/py2/IPython/extensions/autoreload.py +++ b/contrib/python/ipython/py2/IPython/extensions/autoreload.py @@ -186,8 +186,8 @@ class ModuleReloader(object): if not hasattr(module, '__file__') or module.__file__ is None: return None, None - if getattr(module, '__name__', None) in [None, '__mp_main__', '__main__']: - # we cannot reload(__main__) or reload(__mp_main__) + if getattr(module, '__name__', None) in [None, '__mp_main__', '__main__']: + # we cannot reload(__main__) or reload(__mp_main__) return None, None filename = module.__file__ diff --git a/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py b/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py index 1a94e7e0a2..be7a4d6470 100644 --- a/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py +++ b/contrib/python/ipython/py2/IPython/external/qt_for_kernel.py @@ -33,10 +33,10 @@ import sys from IPython.utils.version import check_version from IPython.external.qt_loaders import (load_qt, loaded_api, QT_API_PYSIDE, - QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT5, + QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT5, QT_API_PYQTv1, QT_API_PYQT_DEFAULT) -_qt_apis = (QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT5, QT_API_PYQTv1, +_qt_apis = (QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT, QT_API_PYQT5, QT_API_PYQTv1, QT_API_PYQT_DEFAULT) #Constraints placed on an imported matplotlib @@ -83,8 +83,8 @@ def get_options(): qt_api = os.environ.get('QT_API', None) if qt_api is None: #no ETS variable. Ask mpl, then use default fallback path - return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, - QT_API_PYQT5, QT_API_PYSIDE2] + return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, + QT_API_PYQT5, QT_API_PYSIDE2] elif qt_api not in _qt_apis: raise RuntimeError("Invalid Qt API %r, valid values are: %r" % (qt_api, ', '.join(_qt_apis))) diff --git a/contrib/python/ipython/py2/IPython/external/qt_loaders.py b/contrib/python/ipython/py2/IPython/external/qt_loaders.py index 3b894fb2ab..a9cdf7785c 100644 --- a/contrib/python/ipython/py2/IPython/external/qt_loaders.py +++ b/contrib/python/ipython/py2/IPython/external/qt_loaders.py @@ -20,17 +20,17 @@ QT_API_PYQT5 = 'pyqt5' QT_API_PYQTv1 = 'pyqtv1' # Force version 2 QT_API_PYQT_DEFAULT = 'pyqtdefault' # use system default for version 1 vs. 2 QT_API_PYSIDE = 'pyside' -QT_API_PYSIDE2 = 'pyside2' - -api_to_module = {QT_API_PYSIDE2: 'PySide2', - QT_API_PYSIDE: 'PySide', - QT_API_PYQT: 'PyQt4', - QT_API_PYQTv1: 'PyQt4', - QT_API_PYQT5: 'PyQt5', - QT_API_PYQT_DEFAULT: 'PyQt4', - } +QT_API_PYSIDE2 = 'pyside2' +api_to_module = {QT_API_PYSIDE2: 'PySide2', + QT_API_PYSIDE: 'PySide', + QT_API_PYQT: 'PyQt4', + QT_API_PYQTv1: 'PyQt4', + QT_API_PYQT5: 'PyQt5', + QT_API_PYQT_DEFAULT: 'PyQt4', + } + class ImportDenier(object): """Import Hook that will guard against bad Qt imports once IPython commits to a specific binding @@ -56,28 +56,28 @@ class ImportDenier(object): """ % (fullname, loaded_api())) ID = ImportDenier() -sys.meta_path.insert(0, ID) +sys.meta_path.insert(0, ID) def commit_api(api): """Commit to a particular API, and trigger ImportErrors on subsequent dangerous imports""" - if api == QT_API_PYSIDE2: - ID.forbid('PySide') - ID.forbid('PyQt4') - ID.forbid('PyQt5') + if api == QT_API_PYSIDE2: + ID.forbid('PySide') + ID.forbid('PyQt4') + ID.forbid('PyQt5') if api == QT_API_PYSIDE: - ID.forbid('PySide2') + ID.forbid('PySide2') ID.forbid('PyQt4') ID.forbid('PyQt5') elif api == QT_API_PYQT5: - ID.forbid('PySide2') + ID.forbid('PySide2') ID.forbid('PySide') ID.forbid('PyQt4') else: # There are three other possibilities, all representing PyQt4 ID.forbid('PyQt5') - ID.forbid('PySide2') + ID.forbid('PySide2') ID.forbid('PySide') @@ -89,7 +89,7 @@ def loaded_api(): Returns ------- - None, 'pyside2', 'pyside', 'pyqt', 'pyqt5', or 'pyqtv1' + None, 'pyside2', 'pyside', 'pyqt', 'pyqt5', or 'pyqtv1' """ if 'PyQt4.QtCore' in sys.modules: if qtapi_version() == 2: @@ -98,21 +98,21 @@ def loaded_api(): return QT_API_PYQTv1 elif 'PySide.QtCore' in sys.modules: return QT_API_PYSIDE - elif 'PySide2.QtCore' in sys.modules: - return QT_API_PYSIDE2 + elif 'PySide2.QtCore' in sys.modules: + return QT_API_PYSIDE2 elif 'PyQt5.QtCore' in sys.modules: return QT_API_PYQT5 return None def has_binding(api): - """Safely check for PyQt4/5, PySide or PySide2, without importing submodules - - Supports Python <= 3.3 + """Safely check for PyQt4/5, PySide or PySide2, without importing submodules + Supports Python <= 3.3 + Parameters ---------- - api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault'] + api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault'] Which module to check for Returns @@ -122,7 +122,7 @@ def has_binding(api): # we can't import an incomplete pyside and pyqt4 # this will cause a crash in sip (#1431) # check for complete presence before importing - module_name = api_to_module[api] + module_name = api_to_module[api] import imp try: @@ -132,7 +132,7 @@ def has_binding(api): imp.find_module('QtCore', mod.__path__) imp.find_module('QtGui', mod.__path__) imp.find_module('QtSvg', mod.__path__) - if api in (QT_API_PYQT5, QT_API_PYSIDE2): + if api in (QT_API_PYQT5, QT_API_PYSIDE2): # QT5 requires QtWidgets too imp.find_module('QtWidgets', mod.__path__) @@ -144,49 +144,49 @@ def has_binding(api): except ImportError: return False -def has_binding_new(api): - """Safely check for PyQt4/5, PySide or PySide2, without importing submodules - - Supports Python >= 3.4 - - Parameters - ---------- - api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault'] - Which module to check for - - Returns - ------- - True if the relevant module appears to be importable - """ - module_name = api_to_module[api] - from importlib.util import find_spec - - required = ['QtCore', 'QtGui', 'QtSvg'] - if api in (QT_API_PYQT5, QT_API_PYSIDE2): - # QT5 requires QtWidgets too - required.append('QtWidgets') - - for submod in required: - try: - spec = find_spec('%s.%s' % (module_name, submod)) - except ImportError: - # Package (e.g. PyQt5) not found - return False - else: - if spec is None: - # Submodule (e.g. PyQt5.QtCore) not found - return False - - if api == QT_API_PYSIDE: - # We can also safely check PySide version - import PySide - return check_version(PySide.__version__, '1.0.3') - - return True - -if sys.version_info >= (3, 4): - has_binding = has_binding_new - +def has_binding_new(api): + """Safely check for PyQt4/5, PySide or PySide2, without importing submodules + + Supports Python >= 3.4 + + Parameters + ---------- + api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault'] + Which module to check for + + Returns + ------- + True if the relevant module appears to be importable + """ + module_name = api_to_module[api] + from importlib.util import find_spec + + required = ['QtCore', 'QtGui', 'QtSvg'] + if api in (QT_API_PYQT5, QT_API_PYSIDE2): + # QT5 requires QtWidgets too + required.append('QtWidgets') + + for submod in required: + try: + spec = find_spec('%s.%s' % (module_name, submod)) + except ImportError: + # Package (e.g. PyQt5) not found + return False + else: + if spec is None: + # Submodule (e.g. PyQt5.QtCore) not found + return False + + if api == QT_API_PYSIDE: + # We can also safely check PySide version + import PySide + return check_version(PySide.__version__, '1.0.3') + + return True + +if sys.version_info >= (3, 4): + has_binding = has_binding_new + def qtapi_version(): """Return which QString API has been set, if any @@ -285,23 +285,23 @@ def import_pyside(): from PySide import QtGui, QtCore, QtSvg return QtCore, QtGui, QtSvg, QT_API_PYSIDE -def import_pyside2(): - """ - Import PySide2 - - ImportErrors raised within this function are non-recoverable - """ - from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport - - # Join QtGui and QtWidgets for Qt4 compatibility. - QtGuiCompat = types.ModuleType('QtGuiCompat') - QtGuiCompat.__dict__.update(QtGui.__dict__) - QtGuiCompat.__dict__.update(QtWidgets.__dict__) - QtGuiCompat.__dict__.update(QtPrintSupport.__dict__) - - return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2 - - +def import_pyside2(): + """ + Import PySide2 + + ImportErrors raised within this function are non-recoverable + """ + from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport + + # Join QtGui and QtWidgets for Qt4 compatibility. + QtGuiCompat = types.ModuleType('QtGuiCompat') + QtGuiCompat.__dict__.update(QtGui.__dict__) + QtGuiCompat.__dict__.update(QtWidgets.__dict__) + QtGuiCompat.__dict__.update(QtPrintSupport.__dict__) + + return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2 + + def load_qt(api_options): """ Attempt to import Qt, given a preference list @@ -312,7 +312,7 @@ def load_qt(api_options): Parameters ---------- api_options: List of strings - The order of APIs to try. Valid items are 'pyside', 'pyside2', + The order of APIs to try. Valid items are 'pyside', 'pyside2', 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault' Returns @@ -328,14 +328,14 @@ def load_qt(api_options): bindings (either becaues they aren't installed, or because an incompatible library has already been installed) """ - loaders = { - QT_API_PYSIDE2: import_pyside2, - QT_API_PYSIDE: import_pyside, + loaders = { + QT_API_PYSIDE2: import_pyside2, + QT_API_PYSIDE: import_pyside, QT_API_PYQT: import_pyqt4, QT_API_PYQT5: import_pyqt5, QT_API_PYQTv1: partial(import_pyqt4, version=1), QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None) - } + } for api in api_options: @@ -355,18 +355,18 @@ def load_qt(api_options): else: raise ImportError(""" Could not load requested Qt binding. Please ensure that - PyQt4 >= 4.7, PyQt5, PySide >= 1.0.3 or PySide2 is available, + PyQt4 >= 4.7, PyQt5, PySide >= 1.0.3 or PySide2 is available, and only one is imported per session. Currently-imported Qt library: %r PyQt4 available (requires QtCore, QtGui, QtSvg): %s PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s PySide >= 1.0.3 installed: %s - PySide2 installed: %s + PySide2 installed: %s Tried to load: %r """ % (loaded_api(), has_binding(QT_API_PYQT), has_binding(QT_API_PYQT5), has_binding(QT_API_PYSIDE), - has_binding(QT_API_PYSIDE2), + has_binding(QT_API_PYSIDE2), api_options)) diff --git a/contrib/python/ipython/py2/IPython/frontend.py b/contrib/python/ipython/py2/IPython/frontend.py index 9cc3eaff2f..75dfcdf7fb 100644 --- a/contrib/python/ipython/py2/IPython/frontend.py +++ b/contrib/python/ipython/py2/IPython/frontend.py @@ -17,7 +17,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The top-level `frontend` package has been deprecated since IPython 1.0. " +warn("The top-level `frontend` package has been deprecated since IPython 1.0. " "All its subpackages have been moved to the top `IPython` level.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/html.py b/contrib/python/ipython/py2/IPython/html.py index 050be5c599..99e1717efb 100644 --- a/contrib/python/ipython/py2/IPython/html.py +++ b/contrib/python/ipython/py2/IPython/html.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.html` package has been deprecated since IPython 4.0. " +warn("The `IPython.html` package has been deprecated since IPython 4.0. " "You should import from `notebook` instead. " "`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning) diff --git a/contrib/python/ipython/py2/IPython/kernel/__init__.py b/contrib/python/ipython/py2/IPython/kernel/__init__.py index 70a05ed4aa..3c902b7ffb 100644 --- a/contrib/python/ipython/py2/IPython/kernel/__init__.py +++ b/contrib/python/ipython/py2/IPython/kernel/__init__.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.kernel` package has been deprecated since IPython 4.0." +warn("The `IPython.kernel` package has been deprecated since IPython 4.0." "You should import from ipykernel or jupyter_client instead.", ShimWarning) diff --git a/contrib/python/ipython/py2/IPython/lib/deepreload.py b/contrib/python/ipython/py2/IPython/lib/deepreload.py index 76b493c0bb..aa4836ba76 100644 --- a/contrib/python/ipython/py2/IPython/lib/deepreload.py +++ b/contrib/python/ipython/py2/IPython/lib/deepreload.py @@ -327,8 +327,8 @@ except AttributeError: original_reload = imp.reload # Python 3 # Replacement for reload() -def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__', - 'numpy', 'numpy._globals')): +def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__', + 'numpy', 'numpy._globals')): """Recursively reload all modules used in the given module. Optionally takes a list of modules to exclude from reloading. The default exclude list contains sys, __main__, and __builtin__, to prevent, e.g., resetting diff --git a/contrib/python/ipython/py2/IPython/lib/demo.py b/contrib/python/ipython/py2/IPython/lib/demo.py index b0f3503ed7..419e27a4b3 100644 --- a/contrib/python/ipython/py2/IPython/lib/demo.py +++ b/contrib/python/ipython/py2/IPython/lib/demo.py @@ -106,7 +106,7 @@ the execution. This is probably best explained with the simple example file below. You can copy this into a file named ex_demo.py, and try running it via:: - from IPython.lib.demo import Demo + from IPython.lib.demo import Demo d = Demo('ex_demo.py') d() diff --git a/contrib/python/ipython/py2/IPython/lib/display.py b/contrib/python/ipython/py2/IPython/lib/display.py index 9221e2e062..5d0b644c85 100644 --- a/contrib/python/ipython/py2/IPython/lib/display.py +++ b/contrib/python/ipython/py2/IPython/lib/display.py @@ -251,7 +251,7 @@ class YouTubeVideo(IFrame): start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) Other parameters can be provided as documented at - https://developers.google.com/youtube/player_parameters#Parameters + https://developers.google.com/youtube/player_parameters#Parameters When converting the notebook using nbconvert, a jpeg representation of the video will be inserted in the document. @@ -324,11 +324,11 @@ class FileLink(object): ---------- path : str path to the file or directory that should be formatted - url_prefix : str + url_prefix : str prefix to be prepended to all files to form a working link [default: - ''] + ''] result_html_prefix : str - text to append to beginning to link [default: ''] + text to append to beginning to link [default: ''] result_html_suffix : str text to append at the end of link [default: '<br>'] """ diff --git a/contrib/python/ipython/py2/IPython/lib/editorhooks.py b/contrib/python/ipython/py2/IPython/lib/editorhooks.py index 392557b509..057580b365 100644 --- a/contrib/python/ipython/py2/IPython/lib/editorhooks.py +++ b/contrib/python/ipython/py2/IPython/lib/editorhooks.py @@ -54,7 +54,7 @@ def install_editor(template, wait=False): if sys.platform.startswith('win'): cmd = shlex.split(cmd) proc = subprocess.Popen(cmd, shell=True) - if proc.wait() != 0: + if proc.wait() != 0: raise TryNext() if wait: py3compat.input("Press Enter when done editing:") diff --git a/contrib/python/ipython/py2/IPython/lib/guisupport.py b/contrib/python/ipython/py2/IPython/lib/guisupport.py index 5e13d4343c..b2cc89b57c 100644 --- a/contrib/python/ipython/py2/IPython/lib/guisupport.py +++ b/contrib/python/ipython/py2/IPython/lib/guisupport.py @@ -57,10 +57,10 @@ so you don't have to depend on IPython. """ -# 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 IPython.core.getipython import get_ipython +from IPython.core.getipython import get_ipython #----------------------------------------------------------------------------- # wx @@ -78,15 +78,15 @@ def get_app_wx(*args, **kwargs): def is_event_loop_running_wx(app=None): """Is the wx event loop running.""" - # New way: check attribute on shell instance - ip = get_ipython() - if ip is not None: - if ip.active_eventloop and ip.active_eventloop == 'wx': - return True - # Fall through to checking the application, because Wx has a native way - # to check if the event loop is running, unlike Qt. - - # Old way: check Wx application + # New way: check attribute on shell instance + ip = get_ipython() + if ip is not None: + if ip.active_eventloop and ip.active_eventloop == 'wx': + return True + # Fall through to checking the application, because Wx has a native way + # to check if the event loop is running, unlike Qt. + + # Old way: check Wx application if app is None: app = get_app_wx() if hasattr(app, '_in_event_loop'): @@ -121,12 +121,12 @@ def get_app_qt4(*args, **kwargs): def is_event_loop_running_qt4(app=None): """Is the qt4 event loop running.""" - # New way: check attribute on shell instance - ip = get_ipython() - if ip is not None: - return ip.active_eventloop and ip.active_eventloop.startswith('qt') - - # Old way: check attribute on QApplication singleton + # New way: check attribute on shell instance + ip = get_ipython() + if ip is not None: + return ip.active_eventloop and ip.active_eventloop.startswith('qt') + + # Old way: check attribute on QApplication singleton if app is None: app = get_app_qt4(['']) if hasattr(app, '_in_event_loop'): diff --git a/contrib/python/ipython/py2/IPython/lib/inputhook.py b/contrib/python/ipython/py2/IPython/lib/inputhook.py index e6e8f2dbbc..b82c85a480 100644 --- a/contrib/python/ipython/py2/IPython/lib/inputhook.py +++ b/contrib/python/ipython/py2/IPython/lib/inputhook.py @@ -658,9 +658,9 @@ guis = inputhook_manager.guihooks def _deprecated_disable(): - warn("This function is deprecated since IPython 4.0 use disable_gui() instead", - DeprecationWarning, stacklevel=2) + warn("This function is deprecated since IPython 4.0 use disable_gui() instead", + DeprecationWarning, stacklevel=2) inputhook_manager.disable_gui() - + disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \ disable_pyglet = disable_osx = _deprecated_disable diff --git a/contrib/python/ipython/py2/IPython/lib/pretty.py b/contrib/python/ipython/py2/IPython/lib/pretty.py index 28eee523c5..08ee1de914 100644 --- a/contrib/python/ipython/py2/IPython/lib/pretty.py +++ b/contrib/python/ipython/py2/IPython/lib/pretty.py @@ -96,9 +96,9 @@ __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter', MAX_SEQ_LENGTH = 1000 -# The language spec says that dicts preserve order from 3.7, but CPython -# does so from 3.6, so it seems likely that people will expect that. -DICT_IS_ORDERED = sys.version_info >= (3, 6) +# The language spec says that dicts preserve order from 3.7, but CPython +# does so from 3.6, so it seems likely that people will expect that. +DICT_IS_ORDERED = sys.version_info >= (3, 6) _re_pattern_type = type(re.compile('')) def _safe_getattr(obj, attr, default=None): @@ -122,21 +122,21 @@ else: cast_unicode(text, encoding=get_stream_enc(sys.stdout))) -def _sorted_for_pprint(items): - """ - Sort the given items for pretty printing. Since some predictable - sorting is better than no sorting at all, we sort on the string - representation if normal sorting fails. - """ - items = list(items) - try: - return sorted(items) - except Exception: - try: - return sorted(items, key=str) - except Exception: - return items - +def _sorted_for_pprint(items): + """ + Sort the given items for pretty printing. Since some predictable + sorting is better than no sorting at all, we sort on the string + representation if normal sorting fails. + """ + items = list(items) + try: + return sorted(items) + except Exception: + try: + return sorted(items, key=str) + except Exception: + return items + def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): """ Pretty print the object's representation. @@ -398,10 +398,10 @@ class RepresentationPrinter(PrettyPrinter): meth = cls._repr_pretty_ if callable(meth): return meth(obj, self, cycle) - if cls is not object \ - and callable(cls.__dict__.get('__repr__')): - return _repr_pprint(obj, self, cycle) - + if cls is not object \ + and callable(cls.__dict__.get('__repr__')): + return _repr_pprint(obj, self, cycle) + return _default_pprint(obj, self, cycle) finally: self.end_group() @@ -552,7 +552,7 @@ def _default_pprint(obj, p, cycle): p.end_group(1, '>') -def _seq_pprinter_factory(start, end): +def _seq_pprinter_factory(start, end): """ Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, and lists. @@ -574,7 +574,7 @@ def _seq_pprinter_factory(start, end): return inner -def _set_pprinter_factory(start, end): +def _set_pprinter_factory(start, end): """ Factory that returns a pprint function useful for sets and frozensets. """ @@ -583,15 +583,15 @@ def _set_pprinter_factory(start, end): return p.text(start + '...' + end) if len(obj) == 0: # Special case. - p.text(type(obj).__name__ + '()') + p.text(type(obj).__name__ + '()') else: step = len(start) p.begin_group(step, start) # Like dictionary keys, we will try to sort the items if there aren't too many if not (p.max_seq_length and len(obj) >= p.max_seq_length): - items = _sorted_for_pprint(obj) - else: - items = obj + items = _sorted_for_pprint(obj) + else: + items = obj for idx, x in p._enumerate(items): if idx: p.text(',') @@ -601,7 +601,7 @@ def _set_pprinter_factory(start, end): return inner -def _dict_pprinter_factory(start, end): +def _dict_pprinter_factory(start, end): """ Factory that returns a pprint function used by the default pprint of dicts and dict proxies. @@ -613,10 +613,10 @@ def _dict_pprinter_factory(start, end): p.begin_group(step, start) keys = obj.keys() # if dict isn't large enough to be truncated, sort keys before displaying - # From Python 3.7, dicts preserve order by definition, so we don't sort. - if not DICT_IS_ORDERED \ - and not (p.max_seq_length and len(obj) >= p.max_seq_length): - keys = _sorted_for_pprint(keys) + # From Python 3.7, dicts preserve order by definition, so we don't sort. + if not DICT_IS_ORDERED \ + and not (p.max_seq_length and len(obj) >= p.max_seq_length): + keys = _sorted_for_pprint(keys) for idx, key in p._enumerate(keys): if idx: p.text(',') @@ -743,12 +743,12 @@ _type_pprinters = { int: _repr_pprint, float: _repr_pprint, str: _repr_pprint, - tuple: _seq_pprinter_factory('(', ')'), - list: _seq_pprinter_factory('[', ']'), - dict: _dict_pprinter_factory('{', '}'), + tuple: _seq_pprinter_factory('(', ')'), + list: _seq_pprinter_factory('[', ']'), + dict: _dict_pprinter_factory('{', '}'), - set: _set_pprinter_factory('{', '}'), - frozenset: _set_pprinter_factory('frozenset({', '})'), + set: _set_pprinter_factory('{', '}'), + frozenset: _set_pprinter_factory('frozenset({', '})'), super: _super_pprint, _re_pattern_type: _re_pattern_pprint, type: _type_pprint, diff --git a/contrib/python/ipython/py2/IPython/nbconvert.py b/contrib/python/ipython/py2/IPython/nbconvert.py index 2de4ee50bc..1e708edce8 100644 --- a/contrib/python/ipython/py2/IPython/nbconvert.py +++ b/contrib/python/ipython/py2/IPython/nbconvert.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.nbconvert` package has been deprecated since IPython 4.0. " +warn("The `IPython.nbconvert` package has been deprecated since IPython 4.0. " "You should import from nbconvert instead.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/nbformat.py b/contrib/python/ipython/py2/IPython/nbformat.py index 310277de00..8b24f1d1f1 100644 --- a/contrib/python/ipython/py2/IPython/nbformat.py +++ b/contrib/python/ipython/py2/IPython/nbformat.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.nbformat` package has been deprecated since IPython 4.0. " +warn("The `IPython.nbformat` package has been deprecated since IPython 4.0. " "You should import from nbformat instead.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/parallel.py b/contrib/python/ipython/py2/IPython/parallel.py index 0f10012783..7c107b13c7 100644 --- a/contrib/python/ipython/py2/IPython/parallel.py +++ b/contrib/python/ipython/py2/IPython/parallel.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.parallel` package has been deprecated since IPython 4.0. " +warn("The `IPython.parallel` package has been deprecated since IPython 4.0. " "You should import from ipyparallel instead.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/qt.py b/contrib/python/ipython/py2/IPython/qt.py index 7557a3f329..deee85151e 100644 --- a/contrib/python/ipython/py2/IPython/qt.py +++ b/contrib/python/ipython/py2/IPython/qt.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.qt` package has been deprecated since IPython 4.0. " +warn("The `IPython.qt` package has been deprecated since IPython 4.0. " "You should import from qtconsole instead.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py index 8df9ace1f3..6f550202cb 100644 --- a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py +++ b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py @@ -104,8 +104,8 @@ or :okwarning: options: In [1]: 1/0 In [2]: # raise warning. -To Do ------ +To Do +----- - Turn the ad-hoc test() function into a real test suite. - Break up ipython-specific functionality from matplotlib stuff into better @@ -127,7 +127,7 @@ from __future__ import print_function # Stdlib import atexit -import errno +import errno import os import re import sys @@ -139,7 +139,7 @@ import shutil # Third-party from docutils.parsers.rst import directives -from docutils.parsers.rst import Directive +from docutils.parsers.rst import Directive # Our own from traitlets.config import Config @@ -358,9 +358,9 @@ class EmbeddedSphinxShell(object): source_dir = self.source_dir saveargs = decorator.split(' ') filename = saveargs[1] - # insert relative path to image file in source (as absolute path for Sphinx) - outfile = '/' + os.path.relpath(os.path.join(savefig_dir,filename), - source_dir) + # insert relative path to image file in source (as absolute path for Sphinx) + outfile = '/' + os.path.relpath(os.path.join(savefig_dir,filename), + source_dir) imagerows = ['.. image:: %s'%outfile] @@ -843,8 +843,8 @@ class IPythonDirective(Directive): # get config variables to set figure output directory savefig_dir = config.ipython_savefig_dir - source_dir = self.state.document.settings.env.srcdir - savefig_dir = os.path.join(source_dir, savefig_dir) + source_dir = self.state.document.settings.env.srcdir + savefig_dir = os.path.join(source_dir, savefig_dir) # get regex and prompt stuff rgxin = config.ipython_rgxin @@ -863,12 +863,12 @@ class IPythonDirective(Directive): (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout, mplbackend, exec_lines, hold_count) = self.get_config_options() - try: - os.makedirs(savefig_dir) - except OSError as e: - if e.errno != errno.EEXIST: - raise - + try: + os.makedirs(savefig_dir) + except OSError as e: + if e.errno != errno.EEXIST: + raise + if self.shell is None: # We will be here many times. However, when the # EmbeddedSphinxShell is created, its interactive shell member @@ -977,7 +977,7 @@ def setup(app): setup.app = app app.add_directive('ipython', IPythonDirective) - app.add_config_value('ipython_savefig_dir', 'savefig', 'env') + app.add_config_value('ipython_savefig_dir', 'savefig', 'env') app.add_config_value('ipython_rgxin', re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env') app.add_config_value('ipython_rgxout', diff --git a/contrib/python/ipython/py2/IPython/terminal/console.py b/contrib/python/ipython/py2/IPython/terminal/console.py index 65571a7572..a3e4a7abff 100644 --- a/contrib/python/ipython/py2/IPython/terminal/console.py +++ b/contrib/python/ipython/py2/IPython/terminal/console.py @@ -9,7 +9,7 @@ from warnings import warn from IPython.utils.shimmodule import ShimModule, ShimWarning -warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " +warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " "You should import from jupyter_console instead.", ShimWarning) # Unconditionally insert the shim into sys.modules so that further import calls diff --git a/contrib/python/ipython/py2/IPython/terminal/debugger.py b/contrib/python/ipython/py2/IPython/terminal/debugger.py index c68a3204a6..11819f71cc 100644 --- a/contrib/python/ipython/py2/IPython/terminal/debugger.py +++ b/contrib/python/ipython/py2/IPython/terminal/debugger.py @@ -1,24 +1,24 @@ -import signal -import sys - +import signal +import sys + from IPython.core.debugger import Pdb from IPython.core.completer import IPCompleter from .ptutils import IPythonPTCompleter -from .shortcuts import suspend_to_bg, cursor_in_leading_ws - -from prompt_toolkit.enums import DEFAULT_BUFFER -from prompt_toolkit.filters import (Condition, HasFocus, HasSelection, - ViInsertMode, EmacsInsertMode) -from prompt_toolkit.keys import Keys -from prompt_toolkit.key_binding.manager import KeyBindingManager -from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline +from .shortcuts import suspend_to_bg, cursor_in_leading_ws + +from prompt_toolkit.enums import DEFAULT_BUFFER +from prompt_toolkit.filters import (Condition, HasFocus, HasSelection, + ViInsertMode, EmacsInsertMode) +from prompt_toolkit.keys import Keys +from prompt_toolkit.key_binding.manager import KeyBindingManager +from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline from prompt_toolkit.token import Token from prompt_toolkit.shortcuts import create_prompt_application from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.enums import EditingMode - + class TerminalPdb(Pdb): def __init__(self, *args, **kwargs): Pdb.__init__(self, *args, **kwargs) @@ -29,9 +29,9 @@ class TerminalPdb(Pdb): def get_prompt_tokens(cli): return [(Token.Prompt, self.prompt)] - def patch_stdout(**kwargs): - return self.pt_cli.patch_stdout_context(**kwargs) - + def patch_stdout(**kwargs): + return self.pt_cli.patch_stdout_context(**kwargs) + if self._ptcomp is None: compl = IPCompleter(shell=self.shell, namespace={}, @@ -39,32 +39,32 @@ class TerminalPdb(Pdb): use_readline=False, parent=self.shell, ) - self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout) - - kbmanager = KeyBindingManager.for_prompt() - supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) - kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend - )(suspend_to_bg) - - if self.shell.display_completions == 'readlinelike': - kbmanager.registry.add_binding(Keys.ControlI, - filter=(HasFocus(DEFAULT_BUFFER) - & ~HasSelection() - & ViInsertMode() | EmacsInsertMode() - & ~cursor_in_leading_ws - ))(display_completions_like_readline) - multicolumn = (self.shell.display_completions == 'multicolumn') - + self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout) + + kbmanager = KeyBindingManager.for_prompt() + supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) + kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend + )(suspend_to_bg) + + if self.shell.display_completions == 'readlinelike': + kbmanager.registry.add_binding(Keys.ControlI, + filter=(HasFocus(DEFAULT_BUFFER) + & ~HasSelection() + & ViInsertMode() | EmacsInsertMode() + & ~cursor_in_leading_ws + ))(display_completions_like_readline) + multicolumn = (self.shell.display_completions == 'multicolumn') + self._pt_app = create_prompt_application( editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), - key_bindings_registry=kbmanager.registry, + key_bindings_registry=kbmanager.registry, history=self.shell.debugger_history, completer= self._ptcomp, enable_history_search=True, mouse_support=self.shell.mouse_support, - get_prompt_tokens=get_prompt_tokens, - display_completions_in_columns=multicolumn, - style=self.shell.style + get_prompt_tokens=get_prompt_tokens, + display_completions_in_columns=multicolumn, + style=self.shell.style ) self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop) @@ -104,11 +104,11 @@ class TerminalPdb(Pdb): raise -def set_trace(frame=None): - """ - Start debugging from `frame`. - - If frame is not specified, debugging starts from caller's frame. - """ - TerminalPdb().set_trace(frame or sys._getframe().f_back) - +def set_trace(frame=None): + """ + Start debugging from `frame`. + + If frame is not specified, debugging starts from caller's frame. + """ + TerminalPdb().set_trace(frame or sys._getframe().f_back) + diff --git a/contrib/python/ipython/py2/IPython/terminal/embed.py b/contrib/python/ipython/py2/IPython/terminal/embed.py index 5ad70431e4..f906091dc1 100644 --- a/contrib/python/ipython/py2/IPython/terminal/embed.py +++ b/contrib/python/ipython/py2/IPython/terminal/embed.py @@ -12,7 +12,7 @@ import sys import warnings from IPython.core import ultratb, compilerop -from IPython.core import magic_arguments +from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.interactiveshell import DummyMod, InteractiveShell from IPython.terminal.interactiveshell import TerminalInteractiveShell @@ -28,70 +28,70 @@ class KillEmbeded(Exception):pass class EmbeddedMagics(Magics): @line_magic - @magic_arguments.magic_arguments() - @magic_arguments.argument('-i', '--instance', action='store_true', - help='Kill instance instead of call location') - @magic_arguments.argument('-x', '--exit', action='store_true', - help='Also exit the current session') - @magic_arguments.argument('-y', '--yes', action='store_true', - help='Do not ask confirmation') + @magic_arguments.magic_arguments() + @magic_arguments.argument('-i', '--instance', action='store_true', + help='Kill instance instead of call location') + @magic_arguments.argument('-x', '--exit', action='store_true', + help='Also exit the current session') + @magic_arguments.argument('-y', '--yes', action='store_true', + help='Do not ask confirmation') def kill_embedded(self, parameter_s=''): - """%kill_embedded : deactivate for good the current embedded IPython + """%kill_embedded : deactivate for good the current embedded IPython This function (after asking for confirmation) sets an internal flag so - that an embedded IPython will never activate again for the given call - location. This is useful to permanently disable a shell that is being - called inside a loop: once you've figured out what you needed from it, - you may then kill it and the program will then continue to run without - the interactive shell interfering again. - - - Kill Instance Option - -------------------- - - If for some reasons you need to kill the location where the instance is - created and not called, for example if you create a single instance in - one place and debug in many locations, you can use the ``--instance`` - option to kill this specific instance. Like for the ``call location`` - killing an "instance" should work even if it is recreated within a - loop. - - .. note:: - - This was the default behavior before IPython 5.2 - + that an embedded IPython will never activate again for the given call + location. This is useful to permanently disable a shell that is being + called inside a loop: once you've figured out what you needed from it, + you may then kill it and the program will then continue to run without + the interactive shell interfering again. + + + Kill Instance Option + -------------------- + + If for some reasons you need to kill the location where the instance is + created and not called, for example if you create a single instance in + one place and debug in many locations, you can use the ``--instance`` + option to kill this specific instance. Like for the ``call location`` + killing an "instance" should work even if it is recreated within a + loop. + + .. note:: + + This was the default behavior before IPython 5.2 + """ - args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) - print(args) - if args.instance: - # let no ask - if not args.yes: - kill = ask_yes_no( - "Are you sure you want to kill this embedded instance? [y/N] ", 'n') - else: - kill = True - if kill: - self.shell._disable_init_location() - print("This embedded IPython instance will not reactivate anymore " - "once you exit.") - else: - if not args.yes: - kill = ask_yes_no( - "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') - else: - kill = True - if kill: - self.shell.embedded_active = False - print("This embedded IPython call location will not reactivate anymore " - "once you exit.") - - if args.exit: - # Ask-exit does not really ask, it just set internals flags to exit - # on next loop. - self.shell.ask_exit() - - + args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) + print(args) + if args.instance: + # let no ask + if not args.yes: + kill = ask_yes_no( + "Are you sure you want to kill this embedded instance? [y/N] ", 'n') + else: + kill = True + if kill: + self.shell._disable_init_location() + print("This embedded IPython instance will not reactivate anymore " + "once you exit.") + else: + if not args.yes: + kill = ask_yes_no( + "Are you sure you want to kill this embedded call_location? [y/N] ", 'n') + else: + kill = True + if kill: + self.shell.embedded_active = False + print("This embedded IPython call location will not reactivate anymore " + "once you exit.") + + if args.exit: + # Ask-exit does not really ask, it just set internals flags to exit + # on next loop. + self.shell.ask_exit() + + @line_magic def exit_raise(self, parameter_s=''): """%exit_raise Make the current embedded kernel exit and raise and exception. @@ -126,34 +126,34 @@ class InteractiveShellEmbed(TerminalInteractiveShell): @property def embedded_active(self): - return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ - and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) - - def _disable_init_location(self): - """Disable the current Instance creation location""" - InteractiveShellEmbed._inactive_locations.add(self._init_location_id) + return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\ + and (self._init_location_id not in InteractiveShellEmbed._inactive_locations) + def _disable_init_location(self): + """Disable the current Instance creation location""" + InteractiveShellEmbed._inactive_locations.add(self._init_location_id) + @embedded_active.setter def embedded_active(self, value): - if value: - InteractiveShellEmbed._inactive_locations.discard( - self._call_location_id) - InteractiveShellEmbed._inactive_locations.discard( - self._init_location_id) + if value: + InteractiveShellEmbed._inactive_locations.discard( + self._call_location_id) + InteractiveShellEmbed._inactive_locations.discard( + self._init_location_id) else: - InteractiveShellEmbed._inactive_locations.add( - self._call_location_id) + InteractiveShellEmbed._inactive_locations.add( + self._call_location_id) def __init__(self, **kw): if kw.get('user_global_ns', None) is not None: - raise DeprecationWarning( - "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.") + raise DeprecationWarning( + "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.") - clid = kw.pop('_init_location_id', None) - if not clid: - frame = sys._getframe(1) - clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) - self._init_location_id = clid + clid = kw.pop('_init_location_id', None) + if not clid: + frame = sys._getframe(1) + clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) + self._init_location_id = clid super(InteractiveShellEmbed,self).__init__(**kw) @@ -164,9 +164,9 @@ class InteractiveShellEmbed(TerminalInteractiveShell): call_pdb=self.pdb) def init_sys_modules(self): - """ - Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. - """ + """ + Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. + """ pass def init_magics(self): @@ -174,7 +174,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell): self.register_magics(EmbeddedMagics) def __call__(self, header='', local_ns=None, module=None, dummy=None, - stack_depth=1, global_ns=None, compile_flags=None, **kw): + stack_depth=1, global_ns=None, compile_flags=None, **kw): """Activate the interactive interpreter. __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start @@ -191,16 +191,16 @@ class InteractiveShellEmbed(TerminalInteractiveShell): can still have a specific call work by making it as IPShell(dummy=False). """ - # we are called, set the underlying interactiveshell not to exit. - self.keep_running = True - + # we are called, set the underlying interactiveshell not to exit. + self.keep_running = True + # If the user has turned it off, go away - clid = kw.pop('_call_location_id', None) - if not clid: - frame = sys._getframe(1) - clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) - self._call_location_id = clid - + clid = kw.pop('_call_location_id', None) + if not clid: + frame = sys._getframe(1) + clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) + self._call_location_id = clid + if not self.embedded_active: return @@ -379,10 +379,10 @@ def embed(**kwargs): cls = type(saved_shell_instance) cls.clear_instance() frame = sys._getframe(1) - shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( - frame.f_code.co_filename, frame.f_lineno), **kwargs) - shell(header=header, stack_depth=2, compile_flags=compile_flags, - _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) + shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % ( + frame.f_code.co_filename, frame.f_lineno), **kwargs) + shell(header=header, stack_depth=2, compile_flags=compile_flags, + _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) InteractiveShellEmbed.clear_instance() #restore previous instance if saved_shell_instance is not None: diff --git a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py index f67cc6b502..247235c1fd 100644 --- a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py +++ b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py @@ -8,12 +8,12 @@ from warnings import warn from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC from IPython.utils import io -from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types +from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types from IPython.utils.terminal import toggle_set_term_title, set_term_title from IPython.utils.process import abbrev_cwd -from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union +from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union -from prompt_toolkit.document import Document +from prompt_toolkit.document import Document from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.filters import (HasFocus, Condition, IsDone) from prompt_toolkit.history import InMemoryHistory @@ -23,13 +23,13 @@ from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor from prompt_toolkit.styles import PygmentsStyle, DynamicStyle -from pygments.styles import get_style_by_name -from pygments.style import Style +from pygments.styles import get_style_by_name +from pygments.style import Style from pygments.token import Token from .debugger import TerminalPdb, Pdb from .magics import TerminalMagics -from .pt_inputhooks import get_inputhook_name_and_func +from .pt_inputhooks import get_inputhook_name_and_func from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook from .ptutils import IPythonPTCompleter, IPythonPTLexer from .shortcuts import register_ipython_shortcuts @@ -104,7 +104,7 @@ class TerminalInteractiveShell(InteractiveShell): _pt_app = None simple_prompt = Bool(_use_simple_prompt, - help="""Use `raw_input` for the REPL, without completion and prompt colors. + help="""Use `raw_input` for the REPL, without completion and prompt colors. Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are: IPython own testing machinery, and emacs inferior-shell integration through elpy. @@ -134,21 +134,21 @@ class TerminalInteractiveShell(InteractiveShell): help="Enable mouse support in the prompt" ).tag(config=True) - # We don't load the list of styles for the help string, because loading - # Pygments plugins takes time and can cause unexpected errors. - highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], - help="""The name or class of a Pygments style to use for syntax - highlighting. To see available styles, run `pygmentize -L styles`.""" + # We don't load the list of styles for the help string, because loading + # Pygments plugins takes time and can cause unexpected errors. + highlighting_style = Union([Unicode('legacy'), Type(klass=Style)], + help="""The name or class of a Pygments style to use for syntax + highlighting. To see available styles, run `pygmentize -L styles`.""" ).tag(config=True) - + @observe('highlighting_style') @observe('colors') def _highlighting_style_changed(self, change): self.refresh_style() def refresh_style(self): - self._style = self._make_style_from_name_or_cls(self.highlighting_style) + self._style = self._make_style_from_name_or_cls(self.highlighting_style) highlighting_style_overrides = Dict( @@ -186,7 +186,7 @@ class TerminalInteractiveShell(InteractiveShell): help="Automatically set the terminal title" ).tag(config=True) - display_completions = Enum(('column', 'multicolumn','readlinelike'), + display_completions = Enum(('column', 'multicolumn','readlinelike'), help= ( "Options for displaying tab completions, 'column', 'multicolumn', and " "'readlinelike'. These options are for `prompt_toolkit`, see " "`prompt_toolkit` documentation for more information." @@ -194,14 +194,14 @@ class TerminalInteractiveShell(InteractiveShell): default_value='multicolumn').tag(config=True) highlight_matching_brackets = Bool(True, - help="Highlight matching brackets.", - ).tag(config=True) - - extra_open_editor_shortcuts = Bool(False, - help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. " - "This is in addition to the F2 binding, which is always enabled." + help="Highlight matching brackets.", ).tag(config=True) + extra_open_editor_shortcuts = Bool(False, + help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. " + "This is in addition to the F2 binding, which is always enabled." + ).tag(config=True) + @observe('term_title') def init_term_title(self, change=None): # Enable or disable the terminal title. @@ -215,29 +215,29 @@ class TerminalInteractiveShell(InteractiveShell): super(TerminalInteractiveShell, self).init_display_formatter() # terminal only supports plain text self.display_formatter.active_types = ['text/plain'] - # disable `_ipython_display_` - self.display_formatter.ipython_display_formatter.enabled = False + # disable `_ipython_display_` + self.display_formatter.ipython_display_formatter.enabled = False def init_prompt_toolkit_cli(self): if self.simple_prompt: # Fall back to plain non-interactive output for tests. # This is very limited, and only accepts a single line. def prompt(): - isp = self.input_splitter - prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) - prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) - while isp.push_accepts_more(): - line = cast_unicode_py2(input(prompt_text)) - isp.push(line) - prompt_text = prompt_continuation - return isp.source_reset() + isp = self.input_splitter + prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens()) + prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens()) + while isp.push_accepts_more(): + line = cast_unicode_py2(input(prompt_text)) + isp.push(line) + prompt_text = prompt_continuation + return isp.source_reset() self.prompt_for_code = prompt return # Set up keyboard shortcuts - kbmanager = KeyBindingManager.for_prompt( - enable_open_in_editor=self.extra_open_editor_shortcuts, - ) + kbmanager = KeyBindingManager.for_prompt( + enable_open_in_editor=self.extra_open_editor_shortcuts, + ) register_ipython_shortcuts(kbmanager.registry, self) # Pre-populate history from IPython's history database @@ -249,24 +249,24 @@ class TerminalInteractiveShell(InteractiveShell): cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) - last_cell = cell + last_cell = cell - self._style = self._make_style_from_name_or_cls(self.highlighting_style) - self.style = DynamicStyle(lambda: self._style) + self._style = self._make_style_from_name_or_cls(self.highlighting_style) + self.style = DynamicStyle(lambda: self._style) editing_mode = getattr(EditingMode, self.editing_mode.upper()) - def patch_stdout(**kwargs): - return self.pt_cli.patch_stdout_context(**kwargs) - + def patch_stdout(**kwargs): + return self.pt_cli.patch_stdout_context(**kwargs) + self._pt_app = create_prompt_application( editing_mode=editing_mode, key_bindings_registry=kbmanager.registry, history=history, - completer=IPythonPTCompleter(shell=self, - patch_stdout=patch_stdout), + completer=IPythonPTCompleter(shell=self, + patch_stdout=patch_stdout), enable_history_search=True, - style=self.style, + style=self.style, mouse_support=self.mouse_support, **self._layout_options() ) @@ -275,14 +275,14 @@ class TerminalInteractiveShell(InteractiveShell): self._pt_app, eventloop=self._eventloop, output=create_output(true_color=self.true_color)) - def _make_style_from_name_or_cls(self, name_or_cls): + def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name - We need that to add style for prompt ... etc. + We need that to add style for prompt ... etc. """ style_overrides = {} - if name_or_cls == 'legacy': + if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') @@ -307,26 +307,26 @@ class TerminalInteractiveShell(InteractiveShell): Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', }) - - # Hack: Due to limited color support on the Windows console - # the prompt colors will be wrong without this - if os.name == 'nt': - style_overrides.update({ - Token.Prompt: '#ansidarkgreen', - Token.PromptNum: '#ansigreen bold', - Token.OutPrompt: '#ansidarkred', - Token.OutPromptNum: '#ansired bold', - }) + + # Hack: Due to limited color support on the Windows console + # the prompt colors will be wrong without this + if os.name == 'nt': + style_overrides.update({ + Token.Prompt: '#ansidarkgreen', + Token.PromptNum: '#ansigreen bold', + Token.OutPrompt: '#ansidarkred', + Token.OutPromptNum: '#ansired bold', + }) elif legacy =='nocolor': style_cls=_NoStyle style_overrides = {} else : raise ValueError('Got unknown colors: ', legacy) else : - if isinstance(name_or_cls, string_types): - style_cls = get_style_by_name(name_or_cls) - else: - style_cls = name_or_cls + if isinstance(name_or_cls, string_types): + style_cls = get_style_by_name(name_or_cls) + else: + style_cls = name_or_cls style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', @@ -373,11 +373,11 @@ class TerminalInteractiveShell(InteractiveShell): return document.text def enable_win_unicode_console(self): - if sys.version_info >= (3, 6): - # Since PEP 528, Python uses the unicode APIs for the Windows - # console by default, so WUC shouldn't be needed. - return - + if sys.version_info >= (3, 6): + # Since PEP 528, Python uses the unicode APIs for the Windows + # console by default, so WUC shouldn't be needed. + return + import win_unicode_console if PY3: @@ -451,18 +451,18 @@ class TerminalInteractiveShell(InteractiveShell): def pre_prompt(self): if self.rl_next_input: - # We can't set the buffer here, because it will be reset just after - # this. Adding a callable to pre_run_callables does what we need - # after the buffer is reset. - s = cast_unicode_py2(self.rl_next_input) - def set_doc(): - self.pt_cli.application.buffer.document = Document(s) - if hasattr(self.pt_cli, 'pre_run_callables'): - self.pt_cli.pre_run_callables.append(set_doc) - else: - # Older version of prompt_toolkit; it's OK to set the document - # directly here. - set_doc() + # We can't set the buffer here, because it will be reset just after + # this. Adding a callable to pre_run_callables does what we need + # after the buffer is reset. + s = cast_unicode_py2(self.rl_next_input) + def set_doc(): + self.pt_cli.application.buffer.document = Document(s) + if hasattr(self.pt_cli, 'pre_run_callables'): + self.pt_cli.pre_run_callables.append(set_doc) + else: + # Older version of prompt_toolkit; it's OK to set the document + # directly here. + set_doc() self.rl_next_input = None def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED): @@ -494,28 +494,28 @@ class TerminalInteractiveShell(InteractiveShell): try: self.interact() break - except KeyboardInterrupt as e: - print("\n%s escaped interact()\n" % type(e).__name__) - finally: - # An interrupt during the eventloop will mess up the - # internal state of the prompt_toolkit library. - # Stopping the eventloop fixes this, see - # https://github.com/ipython/ipython/pull/9867 - if hasattr(self, '_eventloop'): - self._eventloop.stop() + except KeyboardInterrupt as e: + print("\n%s escaped interact()\n" % type(e).__name__) + finally: + # An interrupt during the eventloop will mess up the + # internal state of the prompt_toolkit library. + # Stopping the eventloop fixes this, see + # https://github.com/ipython/ipython/pull/9867 + if hasattr(self, '_eventloop'): + self._eventloop.stop() _inputhook = None def inputhook(self, context): if self._inputhook is not None: self._inputhook(context) - active_eventloop = None + active_eventloop = None def enable_gui(self, gui=None): if gui: - self.active_eventloop, self._inputhook =\ - get_inputhook_name_and_func(gui) + self.active_eventloop, self._inputhook =\ + get_inputhook_name_and_func(gui) else: - self.active_eventloop = self._inputhook = None + self.active_eventloop = self._inputhook = None # Run !system commands directly, not through pipes, so terminal programs # work correctly. diff --git a/contrib/python/ipython/py2/IPython/terminal/ipapp.py b/contrib/python/ipython/py2/IPython/terminal/ipapp.py index 6b25aaa3e3..5f6ba29962 100755 --- a/contrib/python/ipython/py2/IPython/terminal/ipapp.py +++ b/contrib/python/ipython/py2/IPython/terminal/ipapp.py @@ -35,7 +35,7 @@ from IPython.extensions.storemagic import StoreMagics from .interactiveshell import TerminalInteractiveShell from IPython.paths import get_ipython_dir from traitlets import ( - Bool, List, Dict, default, observe, Type + Bool, List, Dict, default, observe, Type ) #----------------------------------------------------------------------------- @@ -185,13 +185,13 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): flags = Dict(flags) aliases = Dict(aliases) classes = List() - - interactive_shell_class = Type( - klass=object, # use default_value otherwise which only allow subclasses. - default_value=TerminalInteractiveShell, - help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" - ).tag(config=True) - + + interactive_shell_class = Type( + klass=object, # use default_value otherwise which only allow subclasses. + default_value=TerminalInteractiveShell, + help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends" + ).tag(config=True) + @default('classes') def _classes_default(self): """This has to be in a method, for TerminalIPythonApp to be available.""" @@ -327,7 +327,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): # shell.display_banner should always be False for the terminal # based app, because we call shell.show_banner() by hand below # so the banner shows *before* all extension loading stuff. - self.shell = self.interactive_shell_class.instance(parent=self, + self.shell = self.interactive_shell_class.instance(parent=self, profile_dir=self.profile_dir, ipython_dir=self.ipython_dir, user_ns=self.user_ns) self.shell.configurables.append(self) @@ -365,10 +365,10 @@ def load_default_config(ipython_dir=None): ipython_dir = get_ipython_dir() profile_dir = os.path.join(ipython_dir, 'profile_default') - app = TerminalIPythonApp() - app.config_file_paths.append(profile_dir) - app.load_config_file() - return app.config + app = TerminalIPythonApp() + app.config_file_paths.append(profile_dir) + app.load_config_file() + return app.config launch_new_instance = TerminalIPythonApp.launch_instance diff --git a/contrib/python/ipython/py2/IPython/terminal/magics.py b/contrib/python/ipython/py2/IPython/terminal/magics.py index 3a844a0397..c8b5ea5a35 100644 --- a/contrib/python/ipython/py2/IPython/terminal/magics.py +++ b/contrib/python/ipython/py2/IPython/terminal/magics.py @@ -82,9 +82,9 @@ class TerminalMagics(Magics): @line_magic def autoindent(self, parameter_s = ''): - """Toggle autoindent on/off (deprecated)""" - print("%autoindent is deprecated since IPython 5: you can now paste " - "multiple lines without turning autoindentation off.") + """Toggle autoindent on/off (deprecated)""" + print("%autoindent is deprecated since IPython 5: you can now paste " + "multiple lines without turning autoindentation off.") self.shell.set_autoindent() print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) diff --git a/contrib/python/ipython/py2/IPython/terminal/prompts.py b/contrib/python/ipython/py2/IPython/terminal/prompts.py index 43c2170503..d153289c43 100644 --- a/contrib/python/ipython/py2/IPython/terminal/prompts.py +++ b/contrib/python/ipython/py2/IPython/terminal/prompts.py @@ -63,18 +63,18 @@ class RichPromptDisplayHook(DisplayHook): """Subclass of base display hook using coloured prompt""" def write_output_prompt(self): sys.stdout.write(self.shell.separate_out) - # If we're not displaying a prompt, it effectively ends with a newline, - # because the output will be left-aligned. - self.prompt_end_newline = True - + # If we're not displaying a prompt, it effectively ends with a newline, + # because the output will be left-aligned. + self.prompt_end_newline = True + if self.do_full_cache: tokens = self.shell.prompts.out_prompt_tokens() - prompt_txt = ''.join(s for t, s in tokens) - if prompt_txt and not prompt_txt.endswith('\n'): - # Ask for a newline before multiline output - self.prompt_end_newline = False - + prompt_txt = ''.join(s for t, s in tokens) + if prompt_txt and not prompt_txt.endswith('\n'): + # Ask for a newline before multiline output + self.prompt_end_newline = False + if self.shell.pt_cli: self.shell.pt_cli.print_tokens(tokens) else: - sys.stdout.write(prompt_txt) + sys.stdout.write(prompt_txt) diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py index 3766973e82..3f45bc1cd1 100644 --- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py +++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py @@ -30,20 +30,20 @@ class UnknownBackend(KeyError): "Supported event loops are: {}").format(self.name, ', '.join(backends + sorted(registered))) -def get_inputhook_name_and_func(gui): +def get_inputhook_name_and_func(gui): if gui in registered: - return gui, registered[gui] + return gui, registered[gui] if gui not in backends: raise UnknownBackend(gui) if gui in aliases: - return get_inputhook_name_and_func(aliases[gui]) + return get_inputhook_name_and_func(aliases[gui]) - gui_mod = gui + gui_mod = gui if gui == 'qt5': os.environ['QT_API'] = 'pyqt5' - gui_mod = 'qt' + gui_mod = 'qt' - mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod) - return gui, mod.inputhook + mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod) + return gui, mod.inputhook diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py index 7395ac39eb..536050e8cd 100644 --- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py +++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py @@ -39,11 +39,11 @@ def inputhook(context): else: # On POSIX platforms, we can use a file descriptor to quit the event # loop when there is input ready to read. - notifier = QtCore.QSocketNotifier(context.fileno(), - QtCore.QSocketNotifier.Read) - # connect the callback we care about before we turn it on - notifier.activated.connect(event_loop.exit) + notifier = QtCore.QSocketNotifier(context.fileno(), + QtCore.QSocketNotifier.Read) + # connect the callback we care about before we turn it on + notifier.activated.connect(event_loop.exit) notifier.setEnabled(True) - # only start the event loop we are not already flipped - if not context.input_is_ready(): - event_loop.exec_() + # only start the event loop we are not already flipped + if not context.input_is_ready(): + event_loop.exec_() diff --git a/contrib/python/ipython/py2/IPython/terminal/ptutils.py b/contrib/python/ipython/py2/IPython/terminal/ptutils.py index c9ff705642..03e33155b1 100644 --- a/contrib/python/ipython/py2/IPython/terminal/ptutils.py +++ b/contrib/python/ipython/py2/IPython/terminal/ptutils.py @@ -22,14 +22,14 @@ import pygments.lexers as pygments_lexers class IPythonPTCompleter(Completer): """Adaptor to provide IPython completions to prompt_toolkit""" - def __init__(self, ipy_completer=None, shell=None, patch_stdout=None): + def __init__(self, ipy_completer=None, shell=None, patch_stdout=None): if shell is None and ipy_completer is None: raise TypeError("Please pass shell=an InteractiveShell instance.") self._ipy_completer = ipy_completer self.shell = shell - if patch_stdout is None: - raise TypeError("Please pass patch_stdout") - self.patch_stdout = patch_stdout + if patch_stdout is None: + raise TypeError("Please pass patch_stdout") + self.patch_stdout = patch_stdout @property def ipy_completer(self): @@ -42,14 +42,14 @@ class IPythonPTCompleter(Completer): if not document.current_line.strip(): return - # Some bits of our completion system may print stuff (e.g. if a module - # is imported). This context manager ensures that doesn't interfere with - # the prompt. - with self.patch_stdout(): - used, matches = self.ipy_completer.complete( - line_buffer=document.current_line, - cursor_pos=document.cursor_position_col - ) + # Some bits of our completion system may print stuff (e.g. if a module + # is imported). This context manager ensures that doesn't interfere with + # the prompt. + with self.patch_stdout(): + used, matches = self.ipy_completer.complete( + line_buffer=document.current_line, + cursor_pos=document.cursor_position_col + ) start_pos = -len(used) for m in matches: if not m: diff --git a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py index 8f0ae43e84..71ce01fe9c 100644 --- a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py +++ b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py @@ -62,10 +62,10 @@ def register_ipython_shortcuts(registry, shell): filter=(HasFocus(DEFAULT_BUFFER) & EmacsInsertMode()))(newline_with_copy_margin) - registry.add_binding(Keys.F2, - filter=HasFocus(DEFAULT_BUFFER) - )(open_input_in_editor) - + registry.add_binding(Keys.F2, + filter=HasFocus(DEFAULT_BUFFER) + )(open_input_in_editor) + if shell.display_completions == 'readlinelike': registry.add_binding(Keys.ControlI, filter=(HasFocus(DEFAULT_BUFFER) @@ -96,18 +96,18 @@ def newline_or_execute_outer(shell): b.cancel_completion() return - # If there's only one line, treat it as if the cursor is at the end. - # See https://github.com/ipython/ipython/issues/10425 - if d.line_count == 1: - check_text = d.text - else: - check_text = d.text[:d.cursor_position] - status, indent = shell.input_splitter.check_complete(check_text + '\n') - - if not (d.on_last_line or - d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end() - ): - b.insert_text('\n' + (' ' * (indent or 0))) + # If there's only one line, treat it as if the cursor is at the end. + # See https://github.com/ipython/ipython/issues/10425 + if d.line_count == 1: + check_text = d.text + else: + check_text = d.text[:d.cursor_position] + status, indent = shell.input_splitter.check_complete(check_text + '\n') + + if not (d.on_last_line or + d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end() + ): + b.insert_text('\n' + (' ' * (indent or 0))) return if (status != 'incomplete') and b.accept_action.is_returnable: @@ -181,9 +181,9 @@ def newline_with_copy_margin(event): pos_diff = cursor_start_pos - cursor_end_pos b.cursor_right(count=pos_diff) -def open_input_in_editor(event): - event.cli.current_buffer.tempfile_suffix = ".py" - event.cli.current_buffer.open_in_editor(event.cli) +def open_input_in_editor(event): + event.cli.current_buffer.tempfile_suffix = ".py" + event.cli.current_buffer.open_in_editor(event.cli) if sys.platform == 'win32': diff --git a/contrib/python/ipython/py2/IPython/testing/decorators.py b/contrib/python/ipython/py2/IPython/testing/decorators.py index c9807ce70e..3f18773292 100644 --- a/contrib/python/ipython/py2/IPython/testing/decorators.py +++ b/contrib/python/ipython/py2/IPython/testing/decorators.py @@ -67,7 +67,7 @@ def as_unittest(func): # Utility functions -def apply_wrapper(wrapper, func): +def apply_wrapper(wrapper, func): """Apply a wrapper to a function for decoration. This mixes Michele Simionato's decorator tool with nose's make_decorator, @@ -76,14 +76,14 @@ def apply_wrapper(wrapper, func): This will ensure that wrapped functions can still be well introspected via IPython, for example. """ - warnings.warn("The function `apply_wrapper` is deprecated since IPython 4.0", - DeprecationWarning, stacklevel=2) + warnings.warn("The function `apply_wrapper` is deprecated since IPython 4.0", + DeprecationWarning, stacklevel=2) import nose.tools return decorator(wrapper,nose.tools.make_decorator(func)(wrapper)) -def make_label_dec(label, ds=None): +def make_label_dec(label, ds=None): """Factory function to create a decorator that applies one or more labels. Parameters @@ -128,8 +128,8 @@ def make_label_dec(label, ds=None): True """ - warnings.warn("The function `make_label_dec` is deprecated since IPython 4.0", - DeprecationWarning, stacklevel=2) + warnings.warn("The function `make_label_dec` is deprecated since IPython 4.0", + DeprecationWarning, stacklevel=2) if isinstance(label, string_types): labels = [label] else: @@ -285,8 +285,8 @@ def decorated_dummy(dec, name): import IPython.testing.decorators as dec setup = dec.decorated_dummy(dec.skip_if_no_x11, __name__) """ - warnings.warn("The function `decorated_dummy` is deprecated since IPython 4.0", - DeprecationWarning, stacklevel=2) + warnings.warn("The function `decorated_dummy` is deprecated since IPython 4.0", + DeprecationWarning, stacklevel=2) dummy = lambda: None dummy.__name__ = name return dec(dummy) @@ -319,8 +319,8 @@ skip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg) # not a decorator itself, returns a dummy function to be used as setup def skip_file_no_x11(name): - warnings.warn("The function `skip_file_no_x11` is deprecated since IPython 4.0", - DeprecationWarning, stacklevel=2) + warnings.warn("The function `skip_file_no_x11` is deprecated since IPython 4.0", + DeprecationWarning, stacklevel=2) return decorated_dummy(skip_if_no_x11, name) if _x11_skip_cond else None # Other skip decorators @@ -375,8 +375,8 @@ def onlyif_any_cmd_exists(*commands): """ Decorator to skip test unless at least one of `commands` is found. """ - warnings.warn("The function `onlyif_any_cmd_exists` is deprecated since IPython 4.0", - DeprecationWarning, stacklevel=2) + warnings.warn("The function `onlyif_any_cmd_exists` is deprecated since IPython 4.0", + DeprecationWarning, stacklevel=2) for cmd in commands: if which(cmd): return null_deco diff --git a/contrib/python/ipython/py2/IPython/testing/iptest.py b/contrib/python/ipython/py2/IPython/testing/iptest.py index 4018264125..ed6d55d9bc 100644 --- a/contrib/python/ipython/py2/IPython/testing/iptest.py +++ b/contrib/python/ipython/py2/IPython/testing/iptest.py @@ -50,16 +50,16 @@ if sys.version_info > (3,0): warnings.filterwarnings('error', message=".*{'config': True}.*", category=DeprecationWarning, module='IPy.*') warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*') -warnings.filterwarnings('error', message='.*apply_wrapper.*', category=DeprecationWarning, module='.*') -warnings.filterwarnings('error', message='.*make_label_dec', category=DeprecationWarning, module='.*') -warnings.filterwarnings('error', message='.*decorated_dummy.*', category=DeprecationWarning, module='.*') -warnings.filterwarnings('error', message='.*skip_file_no_x11.*', category=DeprecationWarning, module='.*') -warnings.filterwarnings('error', message='.*onlyif_any_cmd_exists.*', category=DeprecationWarning, module='.*') - -warnings.filterwarnings('error', message='.*disable_gui.*', category=DeprecationWarning, module='.*') - -warnings.filterwarnings('error', message='.*ExceptionColors global is deprecated.*', category=DeprecationWarning, module='.*') - +warnings.filterwarnings('error', message='.*apply_wrapper.*', category=DeprecationWarning, module='.*') +warnings.filterwarnings('error', message='.*make_label_dec', category=DeprecationWarning, module='.*') +warnings.filterwarnings('error', message='.*decorated_dummy.*', category=DeprecationWarning, module='.*') +warnings.filterwarnings('error', message='.*skip_file_no_x11.*', category=DeprecationWarning, module='.*') +warnings.filterwarnings('error', message='.*onlyif_any_cmd_exists.*', category=DeprecationWarning, module='.*') + +warnings.filterwarnings('error', message='.*disable_gui.*', category=DeprecationWarning, module='.*') + +warnings.filterwarnings('error', message='.*ExceptionColors global is deprecated.*', category=DeprecationWarning, module='.*') + if version_info < (6,): # nose.tools renames all things from `camelCase` to `snake_case` which raise an # warning with the runner they also import from standard import library. (as of Dec 2015) diff --git a/contrib/python/ipython/py2/IPython/testing/tools.py b/contrib/python/ipython/py2/IPython/testing/tools.py index 23bf6a68cb..1a2ba6fd43 100644 --- a/contrib/python/ipython/py2/IPython/testing/tools.py +++ b/contrib/python/ipython/py2/IPython/testing/tools.py @@ -7,8 +7,8 @@ Authors from __future__ import absolute_import -# 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 os import re @@ -18,11 +18,11 @@ import tempfile from contextlib import contextmanager from io import StringIO from subprocess import Popen, PIPE -try: - from unittest.mock import patch -except ImportError: - # Python 2 compatibility - from mock import patch +try: + from unittest.mock import patch +except ImportError: + # Python 2 compatibility + from mock import patch try: # These tools are used by parts of the runtime, so we make the nose @@ -438,28 +438,28 @@ def make_tempfile(name): finally: os.unlink(name) -def fake_input(inputs): - """Temporarily replace the input() function to return the given values - - Use as a context manager: - - with fake_input(['result1', 'result2']): - ... - - Values are returned in order. If input() is called again after the last value - was used, EOFError is raised. - """ - it = iter(inputs) - def mock_input(prompt=''): - try: - return next(it) - except StopIteration: - raise EOFError('No more inputs given') - - input_name = '%s.%s' % (py3compat.builtin_mod_name, - 'input' if py3compat.PY3 else 'raw_input') - return patch(input_name, mock_input) - +def fake_input(inputs): + """Temporarily replace the input() function to return the given values + + Use as a context manager: + + with fake_input(['result1', 'result2']): + ... + + Values are returned in order. If input() is called again after the last value + was used, EOFError is raised. + """ + it = iter(inputs) + def mock_input(prompt=''): + try: + return next(it) + except StopIteration: + raise EOFError('No more inputs given') + + input_name = '%s.%s' % (py3compat.builtin_mod_name, + 'input' if py3compat.PY3 else 'raw_input') + return patch(input_name, mock_input) + def help_output_test(subcommand=''): """test that `ipython [subcommand] -h` works""" cmd = get_ipython_cmd() + [subcommand, '-h'] @@ -478,6 +478,6 @@ def help_all_output_test(subcommand=''): nt.assert_equal(rc, 0, err) nt.assert_not_in("Traceback", err) nt.assert_in("Options", out) - nt.assert_in("Class", out) + nt.assert_in("Class", out) return out, err diff --git a/contrib/python/ipython/py2/IPython/utils/_get_terminal_size.py b/contrib/python/ipython/py2/IPython/utils/_get_terminal_size.py index b2c989e7aa..31eef93abd 100644 --- a/contrib/python/ipython/py2/IPython/utils/_get_terminal_size.py +++ b/contrib/python/ipython/py2/IPython/utils/_get_terminal_size.py @@ -1,131 +1,131 @@ -# vendored version of backports.get_terminal_size as nemesapece package are a -# mess and break, especially on ubuntu. This file is under MIT Licence. -# See https://pypi.python.org/pypi/backports.shutil_get_terminal_size -# -# commit: afc5714b1545a5a3aa44cfb5e078d39165bf76ab (Feb 20, 2016) -# from -# https://github.com/chrippa/backports.shutil_get_terminal_size -# -# The MIT License (MIT) -# -# Copyright (c) 2014 Christopher Rosell -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -"""This is a backport of shutil.get_terminal_size from Python 3.3. - -The original implementation is in C, but here we use the ctypes and -fcntl modules to create a pure Python version of os.get_terminal_size. -""" - -import os -import struct -import sys - -from collections import namedtuple - -__all__ = ["get_terminal_size"] - - -terminal_size = namedtuple("terminal_size", "columns lines") - -try: - from ctypes import windll, create_string_buffer, WinError - - _handle_ids = { - 0: -10, - 1: -11, - 2: -12, - } - - def _get_terminal_size(fd): - handle = windll.kernel32.GetStdHandle(_handle_ids[fd]) - if handle == 0: - raise OSError('handle cannot be retrieved') - if handle == -1: - raise WinError() - csbi = create_string_buffer(22) - res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) - if res: - res = struct.unpack("hhhhHhhhhhh", csbi.raw) - left, top, right, bottom = res[5:9] - columns = right - left + 1 - lines = bottom - top + 1 - return terminal_size(columns, lines) - else: - raise WinError() - -except ImportError: - import fcntl - import termios - - def _get_terminal_size(fd): - try: - res = fcntl.ioctl(fd, termios.TIOCGWINSZ, b"\x00" * 4) - except IOError as e: - raise OSError(e) - lines, columns = struct.unpack("hh", res) - - return terminal_size(columns, lines) - - -def get_terminal_size(fallback=(80, 24)): - """Get the size of the terminal window. - - For each of the two dimensions, the environment variable, COLUMNS - and LINES respectively, is checked. If the variable is defined and - the value is a positive integer, it is used. - - When COLUMNS or LINES is not defined, which is the common case, - the terminal connected to sys.__stdout__ is queried - by invoking os.get_terminal_size. - - If the terminal size cannot be successfully queried, either because - the system doesn't support querying, or because we are not - connected to a terminal, the value given in fallback parameter - is used. Fallback defaults to (80, 24) which is the default - size used by many terminal emulators. - - The value returned is a named tuple of type os.terminal_size. - """ - # Try the environment first - try: - columns = int(os.environ["COLUMNS"]) - except (KeyError, ValueError): - columns = 0 - - try: - lines = int(os.environ["LINES"]) - except (KeyError, ValueError): - lines = 0 - - # Only query if necessary - if columns <= 0 or lines <= 0: - try: - size = _get_terminal_size(sys.__stdout__.fileno()) - except (NameError, OSError): - size = terminal_size(*fallback) - - if columns <= 0: - columns = size.columns - if lines <= 0: - lines = size.lines - - return terminal_size(columns, lines) - +# vendored version of backports.get_terminal_size as nemesapece package are a +# mess and break, especially on ubuntu. This file is under MIT Licence. +# See https://pypi.python.org/pypi/backports.shutil_get_terminal_size +# +# commit: afc5714b1545a5a3aa44cfb5e078d39165bf76ab (Feb 20, 2016) +# from +# https://github.com/chrippa/backports.shutil_get_terminal_size +# +# The MIT License (MIT) +# +# Copyright (c) 2014 Christopher Rosell +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +"""This is a backport of shutil.get_terminal_size from Python 3.3. + +The original implementation is in C, but here we use the ctypes and +fcntl modules to create a pure Python version of os.get_terminal_size. +""" + +import os +import struct +import sys + +from collections import namedtuple + +__all__ = ["get_terminal_size"] + + +terminal_size = namedtuple("terminal_size", "columns lines") + +try: + from ctypes import windll, create_string_buffer, WinError + + _handle_ids = { + 0: -10, + 1: -11, + 2: -12, + } + + def _get_terminal_size(fd): + handle = windll.kernel32.GetStdHandle(_handle_ids[fd]) + if handle == 0: + raise OSError('handle cannot be retrieved') + if handle == -1: + raise WinError() + csbi = create_string_buffer(22) + res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) + if res: + res = struct.unpack("hhhhHhhhhhh", csbi.raw) + left, top, right, bottom = res[5:9] + columns = right - left + 1 + lines = bottom - top + 1 + return terminal_size(columns, lines) + else: + raise WinError() + +except ImportError: + import fcntl + import termios + + def _get_terminal_size(fd): + try: + res = fcntl.ioctl(fd, termios.TIOCGWINSZ, b"\x00" * 4) + except IOError as e: + raise OSError(e) + lines, columns = struct.unpack("hh", res) + + return terminal_size(columns, lines) + + +def get_terminal_size(fallback=(80, 24)): + """Get the size of the terminal window. + + For each of the two dimensions, the environment variable, COLUMNS + and LINES respectively, is checked. If the variable is defined and + the value is a positive integer, it is used. + + When COLUMNS or LINES is not defined, which is the common case, + the terminal connected to sys.__stdout__ is queried + by invoking os.get_terminal_size. + + If the terminal size cannot be successfully queried, either because + the system doesn't support querying, or because we are not + connected to a terminal, the value given in fallback parameter + is used. Fallback defaults to (80, 24) which is the default + size used by many terminal emulators. + + The value returned is a named tuple of type os.terminal_size. + """ + # Try the environment first + try: + columns = int(os.environ["COLUMNS"]) + except (KeyError, ValueError): + columns = 0 + + try: + lines = int(os.environ["LINES"]) + except (KeyError, ValueError): + lines = 0 + + # Only query if necessary + if columns <= 0 or lines <= 0: + try: + size = _get_terminal_size(sys.__stdout__.fileno()) + except (NameError, OSError): + size = terminal_size(*fallback) + + if columns <= 0: + columns = size.columns + if lines <= 0: + lines = size.lines + + return terminal_size(columns, lines) + diff --git a/contrib/python/ipython/py2/IPython/utils/_signatures.py b/contrib/python/ipython/py2/IPython/utils/_signatures.py index 20f52b98ed..9ffab265db 100644 --- a/contrib/python/ipython/py2/IPython/utils/_signatures.py +++ b/contrib/python/ipython/py2/IPython/utils/_signatures.py @@ -21,7 +21,7 @@ import itertools import functools import re import types -import inspect +import inspect # patch for single-file @@ -72,7 +72,7 @@ def signature(obj): if not callable(obj): raise TypeError('{0!r} is not a callable object'.format(obj)) - if inspect.ismethod(obj): + if inspect.ismethod(obj): if obj.__self__ is None: # Unbound method - treat it as a function (no distinction in Py 3) obj = obj.__func__ @@ -97,7 +97,7 @@ def signature(obj): else: return signature(wrapped) - if inspect.isfunction(obj): + if inspect.isfunction(obj): return Signature.from_function(obj) if isinstance(obj, functools.partial): @@ -512,7 +512,7 @@ class Signature(object): def from_function(cls, func): '''Constructs Signature for the given python function''' - if not inspect.isfunction(func): + if not inspect.isfunction(func): raise TypeError('{0!r} is not a Python function'.format(func)) Parameter = cls._parameter_cls diff --git a/contrib/python/ipython/py2/IPython/utils/capture.py b/contrib/python/ipython/py2/IPython/utils/capture.py index d8f919568c..e09ff5543e 100644 --- a/contrib/python/ipython/py2/IPython/utils/capture.py +++ b/contrib/python/ipython/py2/IPython/utils/capture.py @@ -21,17 +21,17 @@ else: class RichOutput(object): - def __init__(self, data=None, metadata=None, transient=None, update=False): + def __init__(self, data=None, metadata=None, transient=None, update=False): self.data = data or {} self.metadata = metadata or {} - self.transient = transient or {} - self.update = update - + self.transient = transient or {} + self.update = update + def display(self): from IPython.display import publish_display_data - publish_display_data(data=self.data, metadata=self.metadata, - transient=self.transient, update=self.update) - + publish_display_data(data=self.data, metadata=self.metadata, + transient=self.transient, update=self.update) + def _repr_mime_(self, mime): if mime not in self.data: return @@ -43,22 +43,22 @@ class RichOutput(object): def _repr_html_(self): return self._repr_mime_("text/html") - + def _repr_latex_(self): return self._repr_mime_("text/latex") - + def _repr_json_(self): return self._repr_mime_("application/json") - + def _repr_javascript_(self): return self._repr_mime_("application/javascript") - + def _repr_png_(self): return self._repr_mime_("image/png") - + def _repr_jpeg_(self): return self._repr_mime_("image/jpeg") - + def _repr_svg_(self): return self._repr_mime_("image/svg+xml") @@ -75,35 +75,35 @@ class CapturedIO(object): Additionally, there's a ``c.show()`` method which will print all of the above in the same order, and can be invoked simply via ``c()``. """ - + def __init__(self, stdout, stderr, outputs=None): self._stdout = stdout self._stderr = stderr if outputs is None: outputs = [] self._outputs = outputs - + def __str__(self): return self.stdout - + @property def stdout(self): "Captured standard output" if not self._stdout: return '' return self._stdout.getvalue() - + @property def stderr(self): "Captured standard error" if not self._stderr: return '' return self._stderr.getvalue() - + @property def outputs(self): """A list of the captured rich display outputs, if any. - + If you have a CapturedIO object ``c``, these can be displayed in IPython using:: @@ -111,17 +111,17 @@ class CapturedIO(object): for o in c.outputs: display(o) """ - return [ RichOutput(**kargs) for kargs in self._outputs ] - + return [ RichOutput(**kargs) for kargs in self._outputs ] + def show(self): """write my output to sys.stdout/err as appropriate""" sys.stdout.write(self.stdout) sys.stderr.write(self.stderr) sys.stdout.flush() sys.stderr.flush() - for kargs in self._outputs: - RichOutput(**kargs).display() - + for kargs in self._outputs: + RichOutput(**kargs).display() + __call__ = show @@ -130,27 +130,27 @@ class capture_output(object): stdout = True stderr = True display = True - + def __init__(self, stdout=True, stderr=True, display=True): self.stdout = stdout self.stderr = stderr self.display = display self.shell = None - + def __enter__(self): from IPython.core.getipython import get_ipython from IPython.core.displaypub import CapturingDisplayPublisher - from IPython.core.displayhook import CapturingDisplayHook - + from IPython.core.displayhook import CapturingDisplayHook + self.sys_stdout = sys.stdout self.sys_stderr = sys.stderr - + if self.display: self.shell = get_ipython() if self.shell is None: self.save_display_pub = None self.display = False - + stdout = stderr = outputs = None if self.stdout: stdout = sys.stdout = StringIO() @@ -160,17 +160,17 @@ class capture_output(object): self.save_display_pub = self.shell.display_pub self.shell.display_pub = CapturingDisplayPublisher() outputs = self.shell.display_pub.outputs - self.save_display_hook = sys.displayhook - sys.displayhook = CapturingDisplayHook(shell=self.shell, - outputs=outputs) - + self.save_display_hook = sys.displayhook + sys.displayhook = CapturingDisplayHook(shell=self.shell, + outputs=outputs) + return CapturedIO(stdout, stderr, outputs) - + def __exit__(self, exc_type, exc_value, traceback): sys.stdout = self.sys_stdout sys.stderr = self.sys_stderr if self.display and self.shell: self.shell.display_pub = self.save_display_pub - sys.displayhook = self.save_display_hook + sys.displayhook = self.save_display_hook diff --git a/contrib/python/ipython/py2/IPython/utils/io.py b/contrib/python/ipython/py2/IPython/utils/io.py index 036d6e3926..cbbd094017 100644 --- a/contrib/python/ipython/py2/IPython/utils/io.py +++ b/contrib/python/ipython/py2/IPython/utils/io.py @@ -39,12 +39,12 @@ class IOStream: def clone(meth): return not hasattr(self, meth) and not meth.startswith('_') for meth in filter(clone, dir(stream)): - try: - val = getattr(stream, meth) - except AttributeError: - pass - else: - setattr(self, meth, val) + try: + val = getattr(stream, meth) + except AttributeError: + pass + else: + setattr(self, meth, val) def __repr__(self): cls = self.__class__ diff --git a/contrib/python/ipython/py2/IPython/utils/path.py b/contrib/python/ipython/py2/IPython/utils/path.py index fa850812c7..e4489a71e0 100644 --- a/contrib/python/ipython/py2/IPython/utils/path.py +++ b/contrib/python/ipython/py2/IPython/utils/path.py @@ -77,7 +77,7 @@ def unquote_filename(name, win32=(sys.platform=='win32')): unquoting is now taken care of by :func:`IPython.utils.process.arg_split`. """ warn("'unquote_filename' is deprecated since IPython 5.0 and should not " - "be used anymore", DeprecationWarning, stacklevel=2) + "be used anymore", DeprecationWarning, stacklevel=2) if win32: if name.startswith(("'", '"')) and name.endswith(("'", '"')): name = name[1:-1] @@ -104,7 +104,7 @@ def get_py_filename(name, force_win32=None): if force_win32 is not None: warn("The 'force_win32' argument to 'get_py_filename' is deprecated " "since IPython 5.0 and should not be used anymore", - DeprecationWarning, stacklevel=2) + DeprecationWarning, stacklevel=2) if not os.path.isfile(name) and not name.endswith('.py'): name += '.py' if os.path.isfile(name): @@ -255,31 +255,31 @@ def get_xdg_cache_dir(): @undoc def get_ipython_dir(): - warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) + warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) from IPython.paths import get_ipython_dir return get_ipython_dir() @undoc def get_ipython_cache_dir(): - warn("get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) + warn("get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) from IPython.paths import get_ipython_cache_dir return get_ipython_cache_dir() @undoc def get_ipython_package_dir(): - warn("get_ipython_package_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) + warn("get_ipython_package_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) from IPython.paths import get_ipython_package_dir return get_ipython_package_dir() @undoc def get_ipython_module_path(module_str): - warn("get_ipython_module_path has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) + warn("get_ipython_module_path has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) from IPython.paths import get_ipython_module_path return get_ipython_module_path(module_str) @undoc def locate_profile(profile='default'): - warn("locate_profile has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) + warn("locate_profile has moved to the IPython.paths module since IPython 4.0.", stacklevel=2) from IPython.paths import locate_profile return locate_profile(profile=profile) @@ -370,7 +370,7 @@ def target_update(target,deps,cmd): def filehash(path): """Make an MD5 hash of a file, ignoring any differences in line ending characters.""" - warn("filehash() is deprecated since IPython 4.0", DeprecationWarning, stacklevel=2) + warn("filehash() is deprecated since IPython 4.0", DeprecationWarning, stacklevel=2) with open(path, "rU") as f: return md5(py3compat.str_to_bytes(f.read())).hexdigest() diff --git a/contrib/python/ipython/py2/IPython/utils/terminal.py b/contrib/python/ipython/py2/IPython/utils/terminal.py index e92c410c79..afebe10e52 100644 --- a/contrib/python/ipython/py2/IPython/utils/terminal.py +++ b/contrib/python/ipython/py2/IPython/utils/terminal.py @@ -9,8 +9,8 @@ Authors: * Alexander Belchenko (e-mail: bialix AT ukr.net) """ -from __future__ import absolute_import - +from __future__ import absolute_import + # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. @@ -21,10 +21,10 @@ try: from shutil import get_terminal_size as _get_terminal_size except ImportError: # use backport on Python 2 - try: - from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size - except ImportError: - from ._get_terminal_size import get_terminal_size as _get_terminal_size + try: + from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size + except ImportError: + from ._get_terminal_size import get_terminal_size as _get_terminal_size from . import py3compat |