aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/ipython/py3/IPython/lib
diff options
context:
space:
mode:
authorrobot-contrib <robot-contrib@yandex-team.ru>2022-05-18 00:43:36 +0300
committerrobot-contrib <robot-contrib@yandex-team.ru>2022-05-18 00:43:36 +0300
commit9e5f436a8b2a27bcc7802e443ea3ef3e41a82a75 (patch)
tree78b522cab9f76336e62064d4d8ff7c897659b20e /contrib/python/ipython/py3/IPython/lib
parent8113a823ffca6451bb5ff8f0334560885a939a24 (diff)
downloadydb-9e5f436a8b2a27bcc7802e443ea3ef3e41a82a75.tar.gz
Update contrib/python/ipython/py3 to 8.3.0
ref:e84342d4d30476f9148137f37fd0c6405fd36f55
Diffstat (limited to 'contrib/python/ipython/py3/IPython/lib')
-rw-r--r--contrib/python/ipython/py3/IPython/lib/__init__.py10
-rw-r--r--contrib/python/ipython/py3/IPython/lib/backgroundjobs.py4
-rw-r--r--contrib/python/ipython/py3/IPython/lib/clipboard.py16
-rw-r--r--contrib/python/ipython/py3/IPython/lib/deepreload.py83
-rw-r--r--contrib/python/ipython/py3/IPython/lib/demo.py9
-rw-r--r--contrib/python/ipython/py3/IPython/lib/display.py102
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhook.py666
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookglut.py172
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookgtk.py35
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookgtk3.py34
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookgtk4.py43
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookpyglet.py111
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookqt4.py180
-rw-r--r--contrib/python/ipython/py3/IPython/lib/inputhookwx.py167
-rw-r--r--contrib/python/ipython/py3/IPython/lib/kernel.py13
-rw-r--r--contrib/python/ipython/py3/IPython/lib/latextools.py39
-rw-r--r--contrib/python/ipython/py3/IPython/lib/lexers.py14
-rw-r--r--contrib/python/ipython/py3/IPython/lib/pretty.py212
-rw-r--r--contrib/python/ipython/py3/IPython/lib/security.py114
19 files changed, 269 insertions, 1755 deletions
diff --git a/contrib/python/ipython/py3/IPython/lib/__init__.py b/contrib/python/ipython/py3/IPython/lib/__init__.py
index 8eb89012df..94b8ade4ec 100644
--- a/contrib/python/ipython/py3/IPython/lib/__init__.py
+++ b/contrib/python/ipython/py3/IPython/lib/__init__.py
@@ -9,13 +9,3 @@ Extra capabilities for IPython
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-from IPython.lib.security import passwd
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py3/IPython/lib/backgroundjobs.py b/contrib/python/ipython/py3/IPython/lib/backgroundjobs.py
index 31997e13f2..e7ad51eb67 100644
--- a/contrib/python/ipython/py3/IPython/lib/backgroundjobs.py
+++ b/contrib/python/ipython/py3/IPython/lib/backgroundjobs.py
@@ -116,7 +116,7 @@ class BackgroundJobManager(object):
The given expression is passed to eval(), along with the optional
global/local dicts provided. If no dicts are given, they are
extracted automatically from the caller's frame.
-
+
A Python statement is NOT a valid eval() expression. Basically, you
can only use as an eval() argument something which can go on the right
of an '=' sign and be assigned to a variable.
@@ -135,7 +135,7 @@ class BackgroundJobManager(object):
job_manager.new(myfunc, x, y, kw=dict(z=1))
- The reason for this assymmetry is that the new() method needs to
+ The reason for this asymmetry is that the new() method needs to
maintain access to its own keywords, and this prevents name collisions
between arguments to new() and arguments to your own functions.
diff --git a/contrib/python/ipython/py3/IPython/lib/clipboard.py b/contrib/python/ipython/py3/IPython/lib/clipboard.py
index 316a8ab1f8..95a6b0a0a3 100644
--- a/contrib/python/ipython/py3/IPython/lib/clipboard.py
+++ b/contrib/python/ipython/py3/IPython/lib/clipboard.py
@@ -16,9 +16,9 @@ def win32_clipboard_get():
"""
try:
import win32clipboard
- except ImportError:
+ except ImportError as e:
raise TryNext("Getting text from the clipboard requires the pywin32 "
- "extensions: http://sourceforge.net/projects/pywin32/")
+ "extensions: http://sourceforge.net/projects/pywin32/") from e
win32clipboard.OpenClipboard()
try:
text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
@@ -26,8 +26,8 @@ def win32_clipboard_get():
try:
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
- except (TypeError, win32clipboard.error):
- raise ClipboardEmpty
+ except (TypeError, win32clipboard.error) as e:
+ raise ClipboardEmpty from e
finally:
win32clipboard.CloseClipboard()
return text
@@ -52,15 +52,15 @@ def tkinter_clipboard_get():
"""
try:
from tkinter import Tk, TclError
- except ImportError:
- raise TryNext("Getting text from the clipboard on this platform requires tkinter.")
+ except ImportError as e:
+ raise TryNext("Getting text from the clipboard on this platform requires tkinter.") from e
root = Tk()
root.withdraw()
try:
text = root.clipboard_get()
- except TclError:
- raise ClipboardEmpty
+ except TclError as e:
+ raise ClipboardEmpty from e
finally:
root.destroy()
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
diff --git a/contrib/python/ipython/py3/IPython/lib/deepreload.py b/contrib/python/ipython/py3/IPython/lib/deepreload.py
index bd8c01b2a7..aaedab2425 100644
--- a/contrib/python/ipython/py3/IPython/lib/deepreload.py
+++ b/contrib/python/ipython/py3/IPython/lib/deepreload.py
@@ -28,7 +28,7 @@ re-implementation of hierarchical module import.
import builtins as builtin_mod
from contextlib import contextmanager
-import imp
+import importlib
import sys
from types import ModuleType
@@ -97,21 +97,21 @@ def get_parent(globals, level):
for x in range(level, 1, -1):
try:
dot = name.rindex('.', 0, dot)
- except ValueError:
+ except ValueError as e:
raise ValueError("attempted relative import beyond top-level "
- "package")
+ "package") from e
name = name[:dot]
try:
parent = sys.modules[name]
- except:
+ except BaseException as e:
if orig_level < 1:
warn("Parent module '%.200s' not found while handling absolute "
"import" % name)
parent = None
else:
raise SystemError("Parent module '%.200s' not loaded, cannot "
- "perform relative import" % name)
+ "perform relative import" % name) from e
# We expect, but can't guarantee, if parent != None, that:
# - parent.__name__ == name
@@ -174,33 +174,17 @@ def import_submodule(mod, subname, fullname):
print('Reloading', fullname)
found_now[fullname] = 1
oldm = sys.modules.get(fullname, None)
-
- if mod is None:
- path = None
- elif hasattr(mod, '__path__'):
- path = mod.__path__
- else:
- return None
-
try:
- # This appears to be necessary on Python 3, because imp.find_module()
- # tries to import standard libraries (like io) itself, and we don't
- # want them to be processed by our deep_import_hook.
- with replace_import_hook(original_import):
- fp, filename, stuff = imp.find_module(subname, path)
- except ImportError:
- return None
-
- try:
- m = imp.load_module(fullname, fp, filename, stuff)
+ if oldm is not None:
+ m = importlib.reload(oldm)
+ else:
+ m = importlib.import_module(subname, mod)
except:
# load_module probably removed name from modules because of
# the error. Put back the original module object.
if oldm:
sys.modules[fullname] = oldm
raise
- finally:
- if fp: fp.close()
add_submodule(mod, m, fullname, subname)
@@ -285,50 +269,35 @@ def deep_reload_hook(m):
except:
modules_reloading[name] = m
- dot = name.rfind('.')
- if dot < 0:
- subname = name
- path = None
- else:
- try:
- parent = sys.modules[name[:dot]]
- except KeyError:
- modules_reloading.clear()
- raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
- subname = name[dot+1:]
- path = getattr(parent, "__path__", None)
-
try:
- # This appears to be necessary on Python 3, because imp.find_module()
- # tries to import standard libraries (like io) itself, and we don't
- # want them to be processed by our deep_import_hook.
- with replace_import_hook(original_import):
- fp, filename, stuff = imp.find_module(subname, path)
- finally:
- modules_reloading.clear()
-
- try:
- newm = imp.load_module(name, fp, filename, stuff)
+ newm = importlib.reload(m)
except:
- # load_module probably removed name from modules because of
- # the error. Put back the original module object.
sys.modules[name] = m
raise
finally:
- if fp: fp.close()
-
- modules_reloading.clear()
+ modules_reloading.clear()
return newm
# Save the original hooks
-original_reload = imp.reload
+original_reload = importlib.reload
# Replacement for reload()
-def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__',
- 'numpy', 'numpy._globals')):
+def reload(
+ module,
+ exclude=(
+ *sys.builtin_module_names,
+ "sys",
+ "os.path",
+ "builtins",
+ "__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
+ list contains modules listed in sys.builtin_module_names with additional
+ sys, os.path, builtins and __main__, to prevent, e.g., resetting
display, exception, and io hooks.
"""
global found_now
diff --git a/contrib/python/ipython/py3/IPython/lib/demo.py b/contrib/python/ipython/py3/IPython/lib/demo.py
index 0b19c413c3..8c9ae905d4 100644
--- a/contrib/python/ipython/py3/IPython/lib/demo.py
+++ b/contrib/python/ipython/py3/IPython/lib/demo.py
@@ -184,6 +184,7 @@ import re
import shlex
import sys
import pygments
+from pathlib import Path
from IPython.utils.text import marquee
from IPython.utils import openpy
@@ -238,7 +239,7 @@ class Demo(object):
terminal16m
- style('default'): a string of pygments style name to be used.
- """
+ """
if hasattr(src, "read"):
# It seems to be a file or a file-like object
self.fname = "from a file-like object"
@@ -403,8 +404,8 @@ class Demo(object):
index -= 1
filename = self.shell.mktempfile(self.src_blocks[index])
- self.shell.hooks.editor(filename,1)
- with open(filename, 'r') as f:
+ self.shell.hooks.editor(filename, 1)
+ with open(Path(filename), "r", encoding="utf-8") as f:
new_block = f.read()
# update the source and colored block
self.src_blocks[index] = new_block
@@ -531,7 +532,7 @@ class Demo(object):
elif token[0] == Token.Comment.Single:
toks.append((Token.Comment.Single, token[1][0]))
# parse comment content by rst lexer
- # remove the extrat newline added by rst lexer
+ # remove the extra newline added by rst lexer
toks += list(pygments.lex(token[1][1:], self.rst_lexer))[:-1]
else:
toks.append(token)
diff --git a/contrib/python/ipython/py3/IPython/lib/display.py b/contrib/python/ipython/py3/IPython/lib/display.py
index 7b94acf639..5ff2983dbf 100644
--- a/contrib/python/ipython/py3/IPython/lib/display.py
+++ b/contrib/python/ipython/py3/IPython/lib/display.py
@@ -65,34 +65,47 @@ class Audio(DisplayObject):
Examples
--------
- ::
- # Generate a sound
- import numpy as np
- framerate = 44100
- t = np.linspace(0,5,framerate*5)
- data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
- Audio(data,rate=framerate)
+ >>> import pytest
+ >>> np = pytest.importorskip("numpy")
+
+ Generate a sound
+
+ >>> import numpy as np
+ >>> framerate = 44100
+ >>> t = np.linspace(0,5,framerate*5)
+ >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
+ >>> Audio(data, rate=framerate)
+ <IPython.lib.display.Audio object>
+
+ Can also do stereo or more channels
+
+ >>> dataleft = np.sin(2*np.pi*220*t)
+ >>> dataright = np.sin(2*np.pi*224*t)
+ >>> Audio([dataleft, dataright], rate=framerate)
+ <IPython.lib.display.Audio object>
+
+ From URL:
- # Can also do stereo or more channels
- dataleft = np.sin(2*np.pi*220*t)
- dataright = np.sin(2*np.pi*224*t)
- Audio([dataleft, dataright],rate=framerate)
+ >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP
+ >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP
- Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # From URL
- Audio(url="http://www.w3schools.com/html/horse.ogg")
+ From a File:
- Audio('/path/to/sound.wav') # From file
- Audio(filename='/path/to/sound.ogg')
+ >>> Audio('IPython/lib/tests/test.wav') # doctest: +SKIP
+ >>> Audio(filename='IPython/lib/tests/test.wav') # doctest: +SKIP
- Audio(b'RAW_WAV_DATA..) # From bytes
- Audio(data=b'RAW_WAV_DATA..)
+ From Bytes:
+
+ >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP
+ >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP
See Also
--------
-
- See also the ``Audio`` widgets form the ``ipywidget`` package for more flexibility and options.
-
+ ipywidgets.Audio
+
+ Audio widget with more more flexibility and options.
+
"""
_read_flags = 'rb'
@@ -183,9 +196,9 @@ class Audio(DisplayObject):
try:
max_abs_value = float(max([abs(x) for x in data]))
- except TypeError:
+ except TypeError as e:
raise TypeError('Only lists of mono audio are '
- 'supported if numpy is not installed')
+ 'supported if numpy is not installed') from e
normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data])
@@ -272,10 +285,7 @@ class IFrame(object):
def _repr_html_(self):
"""return the embed iframe"""
if self.params:
- try:
- from urllib.parse import urlencode # Py 3
- except ImportError:
- from urllib import urlencode
+ from urllib.parse import urlencode
params = "?" + urlencode(self.params)
else:
params = ""
@@ -500,27 +510,25 @@ class FileLinks(FileLink):
self.recursive = recursive
- def _get_display_formatter(self,
- dirname_output_format,
- fname_output_format,
- fp_format,
- fp_cleaner=None):
- """ generate built-in formatter function
-
- this is used to define both the notebook and terminal built-in
- formatters as they only differ by some wrapper text for each entry
-
- dirname_output_format: string to use for formatting directory
- names, dirname will be substituted for a single "%s" which
- must appear in this string
- fname_output_format: string to use for formatting file names,
- if a single "%s" appears in the string, fname will be substituted
- if two "%s" appear in the string, the path to fname will be
- substituted for the first and fname will be substituted for the
- second
- fp_format: string to use for formatting filepaths, must contain
- exactly two "%s" and the dirname will be substituted for the first
- and fname will be substituted for the second
+ def _get_display_formatter(
+ self, dirname_output_format, fname_output_format, fp_format, fp_cleaner=None
+ ):
+ """generate built-in formatter function
+
+ this is used to define both the notebook and terminal built-in
+ formatters as they only differ by some wrapper text for each entry
+
+ dirname_output_format: string to use for formatting directory
+ names, dirname will be substituted for a single "%s" which
+ must appear in this string
+ fname_output_format: string to use for formatting file names,
+ if a single "%s" appears in the string, fname will be substituted
+ if two "%s" appear in the string, the path to fname will be
+ substituted for the first and fname will be substituted for the
+ second
+ fp_format: string to use for formatting filepaths, must contain
+ exactly two "%s" and the dirname will be substituted for the first
+ and fname will be substituted for the second
"""
def f(dirname, fnames, included_suffixes=None):
result = []
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhook.py b/contrib/python/ipython/py3/IPython/lib/inputhook.py
deleted file mode 100644
index e6e8f2dbbc..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhook.py
+++ /dev/null
@@ -1,666 +0,0 @@
-# coding: utf-8
-"""
-Deprecated since IPython 5.0
-
-Inputhook management for GUI event loop integration.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-try:
- import ctypes
-except ImportError:
- ctypes = None
-except SystemError: # IronPython issue, 2/8/2014
- ctypes = None
-import os
-import platform
-import sys
-from distutils.version import LooseVersion as V
-
-from warnings import warn
-
-
-warn("`IPython.lib.inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
-
-
-#-----------------------------------------------------------------------------
-# Constants
-#-----------------------------------------------------------------------------
-
-# Constants for identifying the GUI toolkits.
-GUI_WX = 'wx'
-GUI_QT = 'qt'
-GUI_QT4 = 'qt4'
-GUI_GTK = 'gtk'
-GUI_TK = 'tk'
-GUI_OSX = 'osx'
-GUI_GLUT = 'glut'
-GUI_PYGLET = 'pyglet'
-GUI_GTK3 = 'gtk3'
-GUI_NONE = 'none' # i.e. disable
-
-#-----------------------------------------------------------------------------
-# Utilities
-#-----------------------------------------------------------------------------
-
-def _stdin_ready_posix():
- """Return True if there's something to read on stdin (posix version)."""
- infds, outfds, erfds = select.select([sys.stdin],[],[],0)
- return bool(infds)
-
-def _stdin_ready_nt():
- """Return True if there's something to read on stdin (nt version)."""
- return msvcrt.kbhit()
-
-def _stdin_ready_other():
- """Return True, assuming there's something to read on stdin."""
- return True
-
-def _use_appnope():
- """Should we use appnope for dealing with OS X app nap?
-
- Checks if we are on OS X 10.9 or greater.
- """
- return sys.platform == 'darwin' and V(platform.mac_ver()[0]) >= V('10.9')
-
-def _ignore_CTRL_C_posix():
- """Ignore CTRL+C (SIGINT)."""
- signal.signal(signal.SIGINT, signal.SIG_IGN)
-
-def _allow_CTRL_C_posix():
- """Take CTRL+C into account (SIGINT)."""
- signal.signal(signal.SIGINT, signal.default_int_handler)
-
-def _ignore_CTRL_C_other():
- """Ignore CTRL+C (not implemented)."""
- pass
-
-def _allow_CTRL_C_other():
- """Take CTRL+C into account (not implemented)."""
- pass
-
-if os.name == 'posix':
- import select
- import signal
- stdin_ready = _stdin_ready_posix
- ignore_CTRL_C = _ignore_CTRL_C_posix
- allow_CTRL_C = _allow_CTRL_C_posix
-elif os.name == 'nt':
- import msvcrt
- stdin_ready = _stdin_ready_nt
- ignore_CTRL_C = _ignore_CTRL_C_other
- allow_CTRL_C = _allow_CTRL_C_other
-else:
- stdin_ready = _stdin_ready_other
- ignore_CTRL_C = _ignore_CTRL_C_other
- allow_CTRL_C = _allow_CTRL_C_other
-
-
-#-----------------------------------------------------------------------------
-# Main InputHookManager class
-#-----------------------------------------------------------------------------
-
-
-class InputHookManager(object):
- """DEPRECATED since IPython 5.0
-
- Manage PyOS_InputHook for different GUI toolkits.
-
- This class installs various hooks under ``PyOSInputHook`` to handle
- GUI event loop integration.
- """
-
- def __init__(self):
- if ctypes is None:
- warn("IPython GUI event loop requires ctypes, %gui will not be available")
- else:
- self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
- self.guihooks = {}
- self.aliases = {}
- self.apps = {}
- self._reset()
-
- def _reset(self):
- self._callback_pyfunctype = None
- self._callback = None
- self._installed = False
- self._current_gui = None
-
- def get_pyos_inputhook(self):
- """DEPRECATED since IPython 5.0
-
- Return the current PyOS_InputHook as a ctypes.c_void_p."""
- warn("`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
-
- def get_pyos_inputhook_as_func(self):
- """DEPRECATED since IPython 5.0
-
- Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
- warn("`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
-
- def set_inputhook(self, callback):
- """DEPRECATED since IPython 5.0
-
- Set PyOS_InputHook to callback and return the previous one."""
- # On platforms with 'readline' support, it's all too likely to
- # have a KeyboardInterrupt signal delivered *even before* an
- # initial ``try:`` clause in the callback can be executed, so
- # we need to disable CTRL+C in this situation.
- ignore_CTRL_C()
- self._callback = callback
- self._callback_pyfunctype = self.PYFUNC(callback)
- pyos_inputhook_ptr = self.get_pyos_inputhook()
- original = self.get_pyos_inputhook_as_func()
- pyos_inputhook_ptr.value = \
- ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
- self._installed = True
- return original
-
- def clear_inputhook(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Set PyOS_InputHook to NULL and return the previous one.
-
- Parameters
- ----------
- app : optional, ignored
- This parameter is allowed only so that clear_inputhook() can be
- called with a similar interface as all the ``enable_*`` methods. But
- the actual value of the parameter is ignored. This uniform interface
- makes it easier to have user-level entry points in the main IPython
- app like :meth:`enable_gui`."""
- warn("`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- pyos_inputhook_ptr = self.get_pyos_inputhook()
- original = self.get_pyos_inputhook_as_func()
- pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
- allow_CTRL_C()
- self._reset()
- return original
-
- def clear_app_refs(self, gui=None):
- """DEPRECATED since IPython 5.0
-
- Clear IPython's internal reference to an application instance.
-
- Whenever we create an app for a user on qt4 or wx, we hold a
- reference to the app. This is needed because in some cases bad things
- can happen if a user doesn't hold a reference themselves. This
- method is provided to clear the references we are holding.
-
- Parameters
- ----------
- gui : None or str
- If None, clear all app references. If ('wx', 'qt4') clear
- the app for that toolkit. References are not held for gtk or tk
- as those toolkits don't have the notion of an app.
- """
- warn("`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- if gui is None:
- self.apps = {}
- elif gui in self.apps:
- del self.apps[gui]
-
- def register(self, toolkitname, *aliases):
- """DEPRECATED since IPython 5.0
-
- Register a class to provide the event loop for a given GUI.
-
- This is intended to be used as a class decorator. It should be passed
- the names with which to register this GUI integration. The classes
- themselves should subclass :class:`InputHookBase`.
-
- ::
-
- @inputhook_manager.register('qt')
- class QtInputHook(InputHookBase):
- def enable(self, app=None):
- ...
- """
- warn("`register` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- def decorator(cls):
- if ctypes is not None:
- inst = cls(self)
- self.guihooks[toolkitname] = inst
- for a in aliases:
- self.aliases[a] = toolkitname
- return cls
- return decorator
-
- def current_gui(self):
- """DEPRECATED since IPython 5.0
-
- Return a string indicating the currently active GUI or None."""
- warn("`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- return self._current_gui
-
- def enable_gui(self, gui=None, app=None):
- """DEPRECATED since IPython 5.0
-
- Switch amongst GUI input hooks by name.
-
- This is a higher level method than :meth:`set_inputhook` - it uses the
- GUI name to look up a registered object which enables the input hook
- for that GUI.
-
- Parameters
- ----------
- gui : optional, string or None
- If None (or 'none'), clears input hook, otherwise it must be one
- of the recognized GUI names (see ``GUI_*`` constants in module).
-
- app : optional, existing application object.
- For toolkits that have the concept of a global app, you can supply an
- existing one. If not given, the toolkit will be probed for one, and if
- none is found, a new one will be created. Note that GTK does not have
- this concept, and passing an app if ``gui=="GTK"`` will raise an error.
-
- Returns
- -------
- The output of the underlying gui switch routine, typically the actual
- PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
- one.
- """
- warn("`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- if gui in (None, GUI_NONE):
- return self.disable_gui()
-
- if gui in self.aliases:
- return self.enable_gui(self.aliases[gui], app)
-
- try:
- gui_hook = self.guihooks[gui]
- except KeyError:
- e = "Invalid GUI request {!r}, valid ones are: {}"
- raise ValueError(e.format(gui, ', '.join(self.guihooks)))
- self._current_gui = gui
-
- app = gui_hook.enable(app)
- if app is not None:
- app._in_event_loop = True
- self.apps[gui] = app
- return app
-
- def disable_gui(self):
- """DEPRECATED since IPython 5.0
-
- Disable GUI event loop integration.
-
- If an application was registered, this sets its ``_in_event_loop``
- attribute to False. It then calls :meth:`clear_inputhook`.
- """
- warn("`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- gui = self._current_gui
- if gui in self.apps:
- self.apps[gui]._in_event_loop = False
- return self.clear_inputhook()
-
-class InputHookBase(object):
- """DEPRECATED since IPython 5.0
-
- Base class for input hooks for specific toolkits.
-
- Subclasses should define an :meth:`enable` method with one argument, ``app``,
- which will either be an instance of the toolkit's application class, or None.
- They may also define a :meth:`disable` method with no arguments.
- """
- def __init__(self, manager):
- self.manager = manager
-
- def disable(self):
- pass
-
-inputhook_manager = InputHookManager()
-
-@inputhook_manager.register('osx')
-class NullInputHook(InputHookBase):
- """DEPRECATED since IPython 5.0
-
- A null inputhook that doesn't need to do anything"""
- def enable(self, app=None):
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
-
-@inputhook_manager.register('wx')
-class WxInputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with wxPython.
-
- Parameters
- ----------
- app : WX Application, optional.
- Running application to use. If not given, we probe WX for an
- existing application object, and create a new one if none is found.
-
- Notes
- -----
- This methods sets the ``PyOS_InputHook`` for wxPython, which allows
- the wxPython to integrate with terminal based applications like
- IPython.
-
- If ``app`` is not given we probe for an existing one, and return it if
- found. If no existing app is found, we create an :class:`wx.App` as
- follows::
-
- import wx
- app = wx.App(redirect=False, clearSigInt=False)
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- import wx
-
- wx_version = V(wx.__version__).version
-
- if wx_version < [2, 8]:
- raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
-
- from IPython.lib.inputhookwx import inputhook_wx
- self.manager.set_inputhook(inputhook_wx)
- if _use_appnope():
- from appnope import nope
- nope()
-
- import wx
- if app is None:
- app = wx.GetApp()
- if app is None:
- app = wx.App(redirect=False, clearSigInt=False)
-
- return app
-
- def disable(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with wxPython.
-
- This restores appnapp on OS X
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- if _use_appnope():
- from appnope import nap
- nap()
-
-@inputhook_manager.register('qt', 'qt4')
-class Qt4InputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with PyQt4.
-
- Parameters
- ----------
- app : Qt Application, optional.
- Running application to use. If not given, we probe Qt for an
- existing application object, and create a new one if none is found.
-
- Notes
- -----
- This methods sets the PyOS_InputHook for PyQt4, which allows
- the PyQt4 to integrate with terminal based applications like
- IPython.
-
- If ``app`` is not given we probe for an existing one, and return it if
- found. If no existing app is found, we create an :class:`QApplication`
- as follows::
-
- from PyQt4 import QtCore
- app = QtGui.QApplication(sys.argv)
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- from IPython.lib.inputhookqt4 import create_inputhook_qt4
- app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
- self.manager.set_inputhook(inputhook_qt4)
- if _use_appnope():
- from appnope import nope
- nope()
-
- return app
-
- def disable_qt4(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with PyQt4.
-
- This restores appnapp on OS X
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- if _use_appnope():
- from appnope import nap
- nap()
-
-
-@inputhook_manager.register('qt5')
-class Qt5InputHook(Qt4InputHook):
- def enable(self, app=None):
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- os.environ['QT_API'] = 'pyqt5'
- return Qt4InputHook.enable(self, app)
-
-
-@inputhook_manager.register('gtk')
-class GtkInputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with PyGTK.
-
- Parameters
- ----------
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
- This methods sets the PyOS_InputHook for PyGTK, which allows
- the PyGTK to integrate with terminal based applications like
- IPython.
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- import gtk
- try:
- gtk.set_interactive(True)
- except AttributeError:
- # For older versions of gtk, use our own ctypes version
- from IPython.lib.inputhookgtk import inputhook_gtk
- self.manager.set_inputhook(inputhook_gtk)
-
-
-@inputhook_manager.register('tk')
-class TkInputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with Tk.
-
- Parameters
- ----------
- app : toplevel :class:`Tkinter.Tk` widget, optional.
- Running toplevel widget to use. If not given, we probe Tk for an
- existing one, and create a new one if none is found.
-
- Notes
- -----
- If you have already created a :class:`Tkinter.Tk` object, the only
- thing done by this method is to register with the
- :class:`InputHookManager`, since creating that object automatically
- sets ``PyOS_InputHook``.
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- if app is None:
- try:
- from tkinter import Tk # Py 3
- except ImportError:
- from Tkinter import Tk # Py 2
- app = Tk()
- app.withdraw()
- self.manager.apps[GUI_TK] = app
- return app
-
-
-@inputhook_manager.register('glut')
-class GlutInputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with GLUT.
-
- Parameters
- ----------
-
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
-
- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
- integrate with terminal based applications like IPython. Due to GLUT
- limitations, it is currently not possible to start the event loop
- without first creating a window. You should thus not create another
- window but use instead the created one. See 'gui-glut.py' in the
- docs/examples/lib directory.
-
- The default screen mode is set to:
- glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
-
- import OpenGL.GLUT as glut
- from IPython.lib.inputhookglut import glut_display_mode, \
- glut_close, glut_display, \
- glut_idle, inputhook_glut
-
- if GUI_GLUT not in self.manager.apps:
- glut.glutInit( sys.argv )
- glut.glutInitDisplayMode( glut_display_mode )
- # This is specific to freeglut
- if bool(glut.glutSetOption):
- glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
- glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
- glut.glutCreateWindow( sys.argv[0] )
- glut.glutReshapeWindow( 1, 1 )
- glut.glutHideWindow( )
- glut.glutWMCloseFunc( glut_close )
- glut.glutDisplayFunc( glut_display )
- glut.glutIdleFunc( glut_idle )
- else:
- glut.glutWMCloseFunc( glut_close )
- glut.glutDisplayFunc( glut_display )
- glut.glutIdleFunc( glut_idle)
- self.manager.set_inputhook( inputhook_glut )
-
-
- def disable(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with glut.
-
- This sets PyOS_InputHook to NULL and set the display function to a
- dummy one and set the timer to a dummy timer that will be triggered
- very far in the future.
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- import OpenGL.GLUT as glut
- from glut_support import glutMainLoopEvent
-
- glut.glutHideWindow() # This is an event to be processed below
- glutMainLoopEvent()
- super(GlutInputHook, self).disable()
-
-@inputhook_manager.register('pyglet')
-class PygletInputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with pyglet.
-
- Parameters
- ----------
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
- This methods sets the ``PyOS_InputHook`` for pyglet, which allows
- pyglet to integrate with terminal based applications like
- IPython.
-
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- from IPython.lib.inputhookpyglet import inputhook_pyglet
- self.manager.set_inputhook(inputhook_pyglet)
- return app
-
-
-@inputhook_manager.register('gtk3')
-class Gtk3InputHook(InputHookBase):
- def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with Gtk3 (gir bindings).
-
- Parameters
- ----------
- app : ignored
- Ignored, it's only a placeholder to keep the call signature of all
- gui activation methods consistent, which simplifies the logic of
- supporting magics.
-
- Notes
- -----
- This methods sets the PyOS_InputHook for Gtk3, which allows
- the Gtk3 to integrate with terminal based applications like
- IPython.
- """
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
- from IPython.lib.inputhookgtk3 import inputhook_gtk3
- self.manager.set_inputhook(inputhook_gtk3)
-
-
-clear_inputhook = inputhook_manager.clear_inputhook
-set_inputhook = inputhook_manager.set_inputhook
-current_gui = inputhook_manager.current_gui
-clear_app_refs = inputhook_manager.clear_app_refs
-enable_gui = inputhook_manager.enable_gui
-disable_gui = inputhook_manager.disable_gui
-register = inputhook_manager.register
-guis = inputhook_manager.guihooks
-
-
-def _deprecated_disable():
- 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/py3/IPython/lib/inputhookglut.py b/contrib/python/ipython/py3/IPython/lib/inputhookglut.py
deleted file mode 100644
index e6f7f12575..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookglut.py
+++ /dev/null
@@ -1,172 +0,0 @@
-# coding: utf-8
-"""
-GLUT Inputhook support functions
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-# GLUT is quite an old library and it is difficult to ensure proper
-# integration within IPython since original GLUT does not allow to handle
-# events one by one. Instead, it requires for the mainloop to be entered
-# and never returned (there is not even a function to exit he
-# mainloop). Fortunately, there are alternatives such as freeglut
-# (available for linux and windows) and the OSX implementation gives
-# access to a glutCheckLoop() function that blocks itself until a new
-# event is received. This means we have to setup the idle callback to
-# ensure we got at least one event that will unblock the function.
-#
-# Furthermore, it is not possible to install these handlers without a window
-# being first created. We choose to make this window invisible. This means that
-# display mode options are set at this level and user won't be able to change
-# them later without modifying the code. This should probably be made available
-# via IPython options system.
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-import os
-import sys
-import time
-import signal
-import OpenGL.GLUT as glut
-import OpenGL.platform as platform
-from timeit import default_timer as clock
-
-#-----------------------------------------------------------------------------
-# Constants
-#-----------------------------------------------------------------------------
-
-# Frame per second : 60
-# Should probably be an IPython option
-glut_fps = 60
-
-
-# Display mode : double buffeed + rgba + depth
-# Should probably be an IPython option
-glut_display_mode = (glut.GLUT_DOUBLE |
- glut.GLUT_RGBA |
- glut.GLUT_DEPTH)
-
-glutMainLoopEvent = None
-if sys.platform == 'darwin':
- try:
- glutCheckLoop = platform.createBaseFunction(
- 'glutCheckLoop', dll=platform.GLUT, resultType=None,
- argTypes=[],
- doc='glutCheckLoop( ) -> None',
- argNames=(),
- )
- except AttributeError:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions'''
- '''Consider installing freeglut.''')
- glutMainLoopEvent = glutCheckLoop
-elif glut.HAVE_FREEGLUT:
- glutMainLoopEvent = glut.glutMainLoopEvent
-else:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions. '''
- '''Consider installing freeglut.''')
-
-
-#-----------------------------------------------------------------------------
-# Platform-dependent imports and functions
-#-----------------------------------------------------------------------------
-
-if os.name == 'posix':
- import select
-
- def stdin_ready():
- infds, outfds, erfds = select.select([sys.stdin],[],[],0)
- if infds:
- return True
- else:
- return False
-
-elif sys.platform == 'win32':
- import msvcrt
-
- def stdin_ready():
- return msvcrt.kbhit()
-
-#-----------------------------------------------------------------------------
-# Callback functions
-#-----------------------------------------------------------------------------
-
-def glut_display():
- # Dummy display function
- pass
-
-def glut_idle():
- # Dummy idle function
- pass
-
-def glut_close():
- # Close function only hides the current window
- glut.glutHideWindow()
- glutMainLoopEvent()
-
-def glut_int_handler(signum, frame):
- # Catch sigint and print the default message
- signal.signal(signal.SIGINT, signal.default_int_handler)
- print('\nKeyboardInterrupt')
- # Need to reprint the prompt at this stage
-
-
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-def inputhook_glut():
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
-
- signal.signal(signal.SIGINT, glut_int_handler)
-
- try:
- t = clock()
-
- # Make sure the default window is set after a window has been closed
- if glut.glutGetWindow() == 0:
- glut.glutSetWindow( 1 )
- glutMainLoopEvent()
- return 0
-
- while not stdin_ready():
- glutMainLoopEvent()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
- return 0
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhookgtk.py b/contrib/python/ipython/py3/IPython/lib/inputhookgtk.py
deleted file mode 100644
index 98569f54d7..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookgtk.py
+++ /dev/null
@@ -1,35 +0,0 @@
-# encoding: utf-8
-"""
-Enable pygtk to be used interactively by setting PyOS_InputHook.
-
-Authors: Brian Granger
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-import gtk, gobject
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-
-def _main_quit(*args, **kwargs):
- gtk.main_quit()
- return False
-
-def inputhook_gtk():
- gobject.io_add_watch(sys.stdin, gobject.IO_IN, _main_quit)
- gtk.main()
- return 0
-
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhookgtk3.py b/contrib/python/ipython/py3/IPython/lib/inputhookgtk3.py
deleted file mode 100644
index b797e86255..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookgtk3.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# encoding: utf-8
-"""
-Enable Gtk3 to be used interactively by IPython.
-
-Authors: Thomi Richards
-"""
-#-----------------------------------------------------------------------------
-# Copyright (c) 2012, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-from gi.repository import Gtk, GLib
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def _main_quit(*args, **kwargs):
- Gtk.main_quit()
- return False
-
-
-def inputhook_gtk3():
- GLib.io_add_watch(sys.stdin, GLib.PRIORITY_DEFAULT, GLib.IO_IN, _main_quit)
- Gtk.main()
- return 0
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhookgtk4.py b/contrib/python/ipython/py3/IPython/lib/inputhookgtk4.py
deleted file mode 100644
index a872cee36a..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookgtk4.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""
-Enable Gtk4 to be used interactively by IPython.
-"""
-# -----------------------------------------------------------------------------
-# Copyright (c) 2021, the IPython Development Team.
-#
-# Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-# -----------------------------------------------------------------------------
-
-# -----------------------------------------------------------------------------
-# Imports
-# -----------------------------------------------------------------------------
-
-import sys
-
-from gi.repository import GLib
-
-# -----------------------------------------------------------------------------
-# Code
-# -----------------------------------------------------------------------------
-
-
-class _InputHook:
- def __init__(self, context):
- self._quit = False
- GLib.io_add_watch(sys.stdin, GLib.PRIORITY_DEFAULT, GLib.IO_IN, self.quit)
-
- def quit(self, *args, **kwargs):
- self._quit = True
- return False
-
- def run(self):
- context = GLib.MainContext.default()
- while not self._quit:
- context.iteration(True)
-
-
-def inputhook_gtk4():
- hook = _InputHook()
- hook.run()
- return 0
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhookpyglet.py b/contrib/python/ipython/py3/IPython/lib/inputhookpyglet.py
deleted file mode 100644
index fb91ffed17..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookpyglet.py
+++ /dev/null
@@ -1,111 +0,0 @@
-# encoding: utf-8
-"""
-Enable pyglet to be used interactively by setting PyOS_InputHook.
-
-Authors
--------
-
-* Nicolas P. Rougier
-* Fernando Perez
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import sys
-import time
-from timeit import default_timer as clock
-import pyglet
-
-#-----------------------------------------------------------------------------
-# Platform-dependent imports and functions
-#-----------------------------------------------------------------------------
-
-if os.name == 'posix':
- import select
-
- def stdin_ready():
- infds, outfds, erfds = select.select([sys.stdin],[],[],0)
- if infds:
- return True
- else:
- return False
-
-elif sys.platform == 'win32':
- import msvcrt
-
- def stdin_ready():
- return msvcrt.kbhit()
-
-
-# On linux only, window.flip() has a bug that causes an AttributeError on
-# window close. For details, see:
-# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
-
-if sys.platform.startswith('linux'):
- def flip(window):
- try:
- window.flip()
- except AttributeError:
- pass
-else:
- def flip(window):
- window.flip()
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def inputhook_pyglet():
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- t = clock()
- while not stdin_ready():
- pyglet.clock.tick()
- for window in pyglet.app.windows:
- window.switch_to()
- window.dispatch_events()
- window.dispatch_event('on_draw')
- flip(window)
-
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
- return 0
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhookqt4.py b/contrib/python/ipython/py3/IPython/lib/inputhookqt4.py
deleted file mode 100644
index 8a83902fc0..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookqt4.py
+++ /dev/null
@@ -1,180 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-Qt4's inputhook support function
-
-Author: Christian Boos
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import os
-import signal
-import threading
-
-from IPython.core.interactiveshell import InteractiveShell
-from IPython.external.qt_for_kernel import QtCore, QtGui
-from IPython.lib.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready
-
-#-----------------------------------------------------------------------------
-# Module Globals
-#-----------------------------------------------------------------------------
-
-got_kbdint = False
-sigint_timer = None
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def create_inputhook_qt4(mgr, app=None):
- """Create an input hook for running the Qt4 application event loop.
-
- Parameters
- ----------
- mgr : an InputHookManager
-
- app : Qt Application, optional.
- Running application to use. If not given, we probe Qt for an
- existing application object, and create a new one if none is found.
-
- Returns
- -------
- A pair consisting of a Qt Application (either the one given or the
- one found or created) and a inputhook.
-
- Notes
- -----
- We use a custom input hook instead of PyQt4's default one, as it
- interacts better with the readline packages (issue #481).
-
- The inputhook function works in tandem with a 'pre_prompt_hook'
- which automatically restores the hook as an inputhook in case the
- latter has been temporarily disabled after having intercepted a
- KeyboardInterrupt.
- """
-
- if app is None:
- app = QtCore.QCoreApplication.instance()
- if app is None:
- app = QtGui.QApplication([" "])
-
- # Re-use previously created inputhook if any
- ip = InteractiveShell.instance()
- if hasattr(ip, '_inputhook_qt4'):
- return app, ip._inputhook_qt4
-
- # Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
- # hooks (they both share the got_kbdint flag)
-
- def inputhook_qt4():
- """PyOS_InputHook python hook for Qt4.
-
- Process pending Qt events and if there's no pending keyboard
- input, spend a short slice of time (50ms) running the Qt event
- loop.
-
- As a Python ctypes callback can't raise an exception, we catch
- the KeyboardInterrupt and temporarily deactivate the hook,
- which will let a *second* CTRL+C be processed normally and go
- back to a clean prompt line.
- """
- try:
- allow_CTRL_C()
- app = QtCore.QCoreApplication.instance()
- if not app: # shouldn't happen, but safer if it happens anyway...
- return 0
- app.processEvents(QtCore.QEventLoop.AllEvents, 300)
- if not stdin_ready():
- # Generally a program would run QCoreApplication::exec()
- # from main() to enter and process the Qt event loop until
- # quit() or exit() is called and the program terminates.
- #
- # For our input hook integration, we need to repeatedly
- # enter and process the Qt event loop for only a short
- # amount of time (say 50ms) to ensure that Python stays
- # responsive to other user inputs.
- #
- # A naive approach would be to repeatedly call
- # QCoreApplication::exec(), using a timer to quit after a
- # short amount of time. Unfortunately, QCoreApplication
- # emits an aboutToQuit signal before stopping, which has
- # the undesirable effect of closing all modal windows.
- #
- # To work around this problem, we instead create a
- # QEventLoop and call QEventLoop::exec(). Other than
- # setting some state variables which do not seem to be
- # used anywhere, the only thing QCoreApplication adds is
- # the aboutToQuit signal which is precisely what we are
- # trying to avoid.
- timer = QtCore.QTimer()
- event_loop = QtCore.QEventLoop()
- timer.timeout.connect(event_loop.quit)
- while not stdin_ready():
- timer.start(50)
- event_loop.exec_()
- timer.stop()
- except KeyboardInterrupt:
- global got_kbdint, sigint_timer
-
- ignore_CTRL_C()
- got_kbdint = True
- mgr.clear_inputhook()
-
- # This generates a second SIGINT so the user doesn't have to
- # press CTRL+C twice to get a clean prompt.
- #
- # Since we can't catch the resulting KeyboardInterrupt here
- # (because this is a ctypes callback), we use a timer to
- # generate the SIGINT after we leave this callback.
- #
- # Unfortunately this doesn't work on Windows (SIGINT kills
- # Python and CTRL_C_EVENT doesn't work).
- if(os.name == 'posix'):
- pid = os.getpid()
- if(not sigint_timer):
- sigint_timer = threading.Timer(.01, os.kill,
- args=[pid, signal.SIGINT] )
- sigint_timer.start()
- else:
- print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
-
-
- except: # NO exceptions are allowed to escape from a ctypes callback
- ignore_CTRL_C()
- from traceback import print_exc
- print_exc()
- print("Got exception from inputhook_qt4, unregistering.")
- mgr.clear_inputhook()
- finally:
- allow_CTRL_C()
- return 0
-
- def preprompthook_qt4(ishell):
- """'pre_prompt_hook' used to restore the Qt4 input hook
-
- (in case the latter was temporarily deactivated after a
- CTRL+C)
- """
- global got_kbdint, sigint_timer
-
- if(sigint_timer):
- sigint_timer.cancel()
- sigint_timer = None
-
- if got_kbdint:
- mgr.set_inputhook(inputhook_qt4)
- got_kbdint = False
-
- ip._inputhook_qt4 = inputhook_qt4
- ip.set_hook('pre_prompt_hook', preprompthook_qt4)
-
- return app, inputhook_qt4
diff --git a/contrib/python/ipython/py3/IPython/lib/inputhookwx.py b/contrib/python/ipython/py3/IPython/lib/inputhookwx.py
deleted file mode 100644
index 60520a299c..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/inputhookwx.py
+++ /dev/null
@@ -1,167 +0,0 @@
-# encoding: utf-8
-
-"""
-Enable wxPython to be used interactively by setting PyOS_InputHook.
-
-Authors: Robin Dunn, Brian Granger, Ondrej Certik
-"""
-
-#-----------------------------------------------------------------------------
-# Copyright (C) 2008-2011 The IPython Development Team
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-
-import sys
-import signal
-import time
-from timeit import default_timer as clock
-import wx
-
-from IPython.lib.inputhook import stdin_ready
-
-
-#-----------------------------------------------------------------------------
-# Code
-#-----------------------------------------------------------------------------
-
-def inputhook_wx1():
- """Run the wx event loop by processing pending events only.
-
- This approach seems to work, but its performance is not great as it
- relies on having PyOS_InputHook called regularly.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # Make a temporary event loop and process system events until
- # there are no more waiting, then allow idle events (which
- # will also deal with pending or posted wx events.)
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- while evtloop.Pending():
- evtloop.Dispatch()
- app.ProcessIdle()
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-class EventLoopTimer(wx.Timer):
-
- def __init__(self, func):
- self.func = func
- wx.Timer.__init__(self)
-
- def Notify(self):
- self.func()
-
-class EventLoopRunner(object):
-
- def Run(self, time):
- self.evtloop = wx.EventLoop()
- self.timer = EventLoopTimer(self.check_stdin)
- self.timer.Start(time)
- self.evtloop.Run()
-
- def check_stdin(self):
- if stdin_ready():
- self.timer.Stop()
- self.evtloop.Exit()
-
-def inputhook_wx2():
- """Run the wx event loop, polling for stdin.
-
- This version runs the wx eventloop for an undetermined amount of time,
- during which it periodically checks to see if anything is ready on
- stdin. If anything is ready on stdin, the event loop exits.
-
- The argument to elr.Run controls how often the event loop looks at stdin.
- This determines the responsiveness at the keyboard. A setting of 1000
- enables a user to type at most 1 char per second. I have found that a
- setting of 10 gives good keyboard response. We can shorten it further,
- but eventually performance would suffer from calling select/kbhit too
- often.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
- elr = EventLoopRunner()
- # As this time is made shorter, keyboard response improves, but idle
- # CPU load goes up. 10 ms seems like a good compromise.
- elr.Run(time=10) # CHANGE time here to control polling interval
- except KeyboardInterrupt:
- pass
- return 0
-
-def inputhook_wx3():
- """Run the wx event loop by processing pending events only.
-
- This is like inputhook_wx1, but it keeps processing pending events
- until stdin is ready. After processing all pending events, a call to
- time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
- This sleep time should be tuned though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # The import of wx on Linux sets the handler for signal.SIGINT
- # to 0. This is a bug in wx or gtk. We fix by just setting it
- # back to the Python default.
- if not callable(signal.getsignal(signal.SIGINT)):
- signal.signal(signal.SIGINT, signal.default_int_handler)
-
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- t = clock()
- while not stdin_ready():
- while evtloop.Pending():
- t = clock()
- evtloop.Dispatch()
- app.ProcessIdle()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-if sys.platform == 'darwin':
- # On OSX, evtloop.Pending() always returns True, regardless of there being
- # any events pending. As such we can't use implementations 1 or 3 of the
- # inputhook as those depend on a pending/dispatch loop.
- inputhook_wx = inputhook_wx2
-else:
- # This is our default implementation
- inputhook_wx = inputhook_wx3
diff --git a/contrib/python/ipython/py3/IPython/lib/kernel.py b/contrib/python/ipython/py3/IPython/lib/kernel.py
deleted file mode 100644
index af9827667f..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/kernel.py
+++ /dev/null
@@ -1,13 +0,0 @@
-"""[DEPRECATED] Utilities for connecting to kernels
-
-Moved to IPython.kernel.connect
-"""
-
-import warnings
-warnings.warn("IPython.lib.kernel moved to IPython.kernel.connect in IPython 1.0,"
- " and will be removed in IPython 6.0.",
- DeprecationWarning
-)
-
-from ipykernel.connect import *
-
diff --git a/contrib/python/ipython/py3/IPython/lib/latextools.py b/contrib/python/ipython/py3/IPython/lib/latextools.py
index f976f2edb1..27aeef5b0e 100644
--- a/contrib/python/ipython/py3/IPython/lib/latextools.py
+++ b/contrib/python/ipython/py3/IPython/lib/latextools.py
@@ -12,6 +12,8 @@ import subprocess
from base64 import encodebytes
import textwrap
+from pathlib import Path, PurePath
+
from IPython.utils.process import find_cmd, FindCmdError
from traitlets.config import get_config
from traitlets.config.configurable import SingletonConfigurable
@@ -75,7 +77,6 @@ def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black',
format, e.g. '#AA20FA'.
scale : float
Scale factor for the resulting PNG.
-
None is returned when the backend cannot be used.
"""
@@ -95,8 +96,8 @@ def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black',
try:
color = "RGB {}".format(" ".join([str(int(x, 16)) for x in
textwrap.wrap(color[1:], 2)]))
- except ValueError:
- raise ValueError('Invalid color specification {}.'.format(color))
+ except ValueError as e:
+ raise ValueError('Invalid color specification {}.'.format(color)) from e
else:
raise ValueError('Invalid color specification {}.'.format(color))
else:
@@ -109,7 +110,8 @@ def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black',
def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
try:
- from matplotlib import mathtext
+ from matplotlib import figure, font_manager, mathtext
+ from matplotlib.backends import backend_agg
from pyparsing import ParseFatalException
except ImportError:
return None
@@ -120,11 +122,18 @@ def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
s = u'${0}$'.format(s)
try:
- mt = mathtext.MathTextParser('bitmap')
- f = BytesIO()
- dpi = 120*scale
- mt.to_png(f, s, fontsize=12, dpi=dpi, color=color)
- return f.getvalue()
+ prop = font_manager.FontProperties(size=12)
+ dpi = 120 * scale
+ buffer = BytesIO()
+
+ # Adapted from mathtext.math_to_image
+ parser = mathtext.MathTextParser("path")
+ width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
+ fig = figure.Figure(figsize=(width / 72, height / 72))
+ fig.text(0, depth / height, s, fontproperties=prop, color=color)
+ backend_agg.FigureCanvasAgg(fig)
+ fig.savefig(buffer, dpi=dpi, format="png", transparent=True)
+ return buffer.getvalue()
except (ValueError, RuntimeError, ParseFatalException):
return None
@@ -136,12 +145,12 @@ def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
except FindCmdError:
return None
try:
- workdir = tempfile.mkdtemp()
- tmpfile = os.path.join(workdir, "tmp.tex")
- dvifile = os.path.join(workdir, "tmp.dvi")
- outfile = os.path.join(workdir, "tmp.png")
+ workdir = Path(tempfile.mkdtemp())
+ tmpfile = workdir.joinpath("tmp.tex")
+ dvifile = workdir.joinpath("tmp.dvi")
+ outfile = workdir.joinpath("tmp.png")
- with open(tmpfile, "w", encoding='utf8') as f:
+ with tmpfile.open("w", encoding="utf8") as f:
f.writelines(genelatex(s, wrap))
with open(os.devnull, 'wb') as devnull:
@@ -172,7 +181,7 @@ def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
stderr=devnull,
)
- with open(outfile, "rb") as f:
+ with outfile.open("rb") as f:
return f.read()
except subprocess.CalledProcessError:
return None
diff --git a/contrib/python/ipython/py3/IPython/lib/lexers.py b/contrib/python/ipython/py3/IPython/lib/lexers.py
index 4494da5657..0c9b6e1bc7 100644
--- a/contrib/python/ipython/py3/IPython/lib/lexers.py
+++ b/contrib/python/ipython/py3/IPython/lib/lexers.py
@@ -221,11 +221,9 @@ class IPythonConsoleLexer(Lexer):
In [2]: a
Out[2]: 'foo'
- In [3]: print a
+ In [3]: print(a)
foo
- In [4]: 1 / 0
-
Support is also provided for IPython exceptions:
@@ -234,13 +232,9 @@ class IPythonConsoleLexer(Lexer):
.. code-block:: ipythonconsole
In [1]: raise Exception
-
- ---------------------------------------------------------------------------
- Exception Traceback (most recent call last)
- <ipython-input-1-fca2ab0ca76b> in <module>
- ----> 1 raise Exception
-
- Exception:
+ Traceback (most recent call last):
+ ...
+ Exception
"""
name = 'IPython console session'
diff --git a/contrib/python/ipython/py3/IPython/lib/pretty.py b/contrib/python/ipython/py3/IPython/lib/pretty.py
index 1cb46b1413..72f143522d 100644
--- a/contrib/python/ipython/py3/IPython/lib/pretty.py
+++ b/contrib/python/ipython/py3/IPython/lib/pretty.py
@@ -34,6 +34,22 @@ pretty printer passed::
def _repr_pretty_(self, p, cycle):
...
+Here's an example for a class with a simple constructor::
+
+ class MySimpleObject:
+
+ def __init__(self, a, b, *, c=None):
+ self.a = a
+ self.b = b
+ self.c = c
+
+ def _repr_pretty_(self, p, cycle):
+ ctor = CallExpression.factory(self.__class__.__name__)
+ if self.c is None:
+ p.pretty(ctor(a, b))
+ else:
+ p.pretty(ctor(a, b, c=c))
+
Here is an example implementation of a `_repr_pretty_` method for a list
subclass::
@@ -93,7 +109,7 @@ from IPython.utils.decorators import undoc
from IPython.utils.py3compat import PYPY
__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
- 'for_type', 'for_type_by_name']
+ 'for_type', 'for_type_by_name', 'RawText', 'RawStringLiteral', 'CallExpression']
MAX_SEQ_LENGTH = 1000
@@ -500,6 +516,75 @@ class GroupQueue(object):
pass
+class RawText:
+ """ Object such that ``p.pretty(RawText(value))`` is the same as ``p.text(value)``.
+
+ An example usage of this would be to show a list as binary numbers, using
+ ``p.pretty([RawText(bin(i)) for i in integers])``.
+ """
+ def __init__(self, value):
+ self.value = value
+
+ def _repr_pretty_(self, p, cycle):
+ p.text(self.value)
+
+
+class CallExpression:
+ """ Object which emits a line-wrapped call expression in the form `__name(*args, **kwargs)` """
+ def __init__(__self, __name, *args, **kwargs):
+ # dunders are to avoid clashes with kwargs, as python's name manging
+ # will kick in.
+ self = __self
+ self.name = __name
+ self.args = args
+ self.kwargs = kwargs
+
+ @classmethod
+ def factory(cls, name):
+ def inner(*args, **kwargs):
+ return cls(name, *args, **kwargs)
+ return inner
+
+ def _repr_pretty_(self, p, cycle):
+ # dunders are to avoid clashes with kwargs, as python's name manging
+ # will kick in.
+
+ started = False
+ def new_item():
+ nonlocal started
+ if started:
+ p.text(",")
+ p.breakable()
+ started = True
+
+ prefix = self.name + "("
+ with p.group(len(prefix), prefix, ")"):
+ for arg in self.args:
+ new_item()
+ p.pretty(arg)
+ for arg_name, arg in self.kwargs.items():
+ new_item()
+ arg_prefix = arg_name + "="
+ with p.group(len(arg_prefix), arg_prefix):
+ p.pretty(arg)
+
+
+class RawStringLiteral:
+ """ Wrapper that shows a string with a `r` prefix """
+ def __init__(self, value):
+ self.value = value
+
+ def _repr_pretty_(self, p, cycle):
+ base_repr = repr(self.value)
+ if base_repr[:1] in 'uU':
+ base_repr = base_repr[1:]
+ prefix = 'ur'
+ else:
+ prefix = 'r'
+ base_repr = prefix + base_repr.replace('\\\\', '\\')
+ p.text(base_repr)
+
+
def _default_pprint(obj, p, cycle):
"""
The default print function. Used if an object does not provide one and
@@ -541,7 +626,7 @@ def _default_pprint(obj, p, cycle):
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.
+ the default pprint for tuples and lists.
"""
def inner(obj, p, cycle):
if cycle:
@@ -553,7 +638,7 @@ def _seq_pprinter_factory(start, end):
p.text(',')
p.breakable()
p.pretty(x)
- if len(obj) == 1 and type(obj) is tuple:
+ if len(obj) == 1 and isinstance(obj, tuple):
# Special case for 1-item tuples.
p.text(',')
p.end_group(step, end)
@@ -623,45 +708,38 @@ def _super_pprint(obj, p, cycle):
p.end_group(8, '>')
-def _re_pattern_pprint(obj, p, cycle):
- """The pprint function for regular expression patterns."""
- p.text('re.compile(')
- pattern = repr(obj.pattern)
- if pattern[:1] in 'uU':
- pattern = pattern[1:]
- prefix = 'ur'
- else:
- prefix = 'r'
- pattern = prefix + pattern.replace('\\\\', '\\')
- p.text(pattern)
- if obj.flags:
- p.text(',')
- p.breakable()
+
+class _ReFlags:
+ def __init__(self, value):
+ self.value = value
+
+ def _repr_pretty_(self, p, cycle):
done_one = False
for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
'UNICODE', 'VERBOSE', 'DEBUG'):
- if obj.flags & getattr(re, flag):
+ if self.value & getattr(re, flag):
if done_one:
p.text('|')
p.text('re.' + flag)
done_one = True
- p.text(')')
+
+
+def _re_pattern_pprint(obj, p, cycle):
+ """The pprint function for regular expression patterns."""
+ re_compile = CallExpression.factory('re.compile')
+ if obj.flags:
+ p.pretty(re_compile(RawStringLiteral(obj.pattern), _ReFlags(obj.flags)))
+ else:
+ p.pretty(re_compile(RawStringLiteral(obj.pattern)))
def _types_simplenamespace_pprint(obj, p, cycle):
"""The pprint function for types.SimpleNamespace."""
- name = 'namespace'
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- else:
- for idx, (attr, value) in enumerate(obj.__dict__.items()):
- if idx:
- p.text(',')
- p.breakable()
- attr_kwarg = '{}='.format(attr)
- with p.group(len(attr_kwarg), attr_kwarg):
- p.pretty(value)
+ namespace = CallExpression.factory('namespace')
+ if cycle:
+ p.pretty(namespace(RawText("...")))
+ else:
+ p.pretty(namespace(**obj.__dict__))
def _type_pprint(obj, p, cycle):
@@ -724,14 +802,8 @@ def _exception_pprint(obj, p, cycle):
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
- step = len(name) + 1
- p.begin_group(step, name + '(')
- for idx, arg in enumerate(getattr(obj, 'args', ())):
- if idx:
- p.text(',')
- p.breakable()
- p.pretty(arg)
- p.end_group(step, ')')
+
+ p.pretty(CallExpression(name, *getattr(obj, 'args', ())))
#: the exception base
@@ -817,45 +889,51 @@ _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
def _defaultdict_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- else:
- p.pretty(obj.default_factory)
- p.text(',')
- p.breakable()
- p.pretty(dict(obj))
+ cls_ctor = CallExpression.factory(obj.__class__.__name__)
+ if cycle:
+ p.pretty(cls_ctor(RawText("...")))
+ else:
+ p.pretty(cls_ctor(obj.default_factory, dict(obj)))
def _ordereddict_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- elif len(obj):
- p.pretty(list(obj.items()))
+ cls_ctor = CallExpression.factory(obj.__class__.__name__)
+ if cycle:
+ p.pretty(cls_ctor(RawText("...")))
+ elif len(obj):
+ p.pretty(cls_ctor(list(obj.items())))
+ else:
+ p.pretty(cls_ctor())
def _deque_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- else:
- p.pretty(list(obj))
-
+ cls_ctor = CallExpression.factory(obj.__class__.__name__)
+ if cycle:
+ p.pretty(cls_ctor(RawText("...")))
+ else:
+ p.pretty(cls_ctor(list(obj)))
def _counter_pprint(obj, p, cycle):
- name = obj.__class__.__name__
- with p.group(len(name) + 1, name + '(', ')'):
- if cycle:
- p.text('...')
- elif len(obj):
- p.pretty(dict(obj))
+ cls_ctor = CallExpression.factory(obj.__class__.__name__)
+ if cycle:
+ p.pretty(cls_ctor(RawText("...")))
+ elif len(obj):
+ p.pretty(cls_ctor(dict(obj)))
+ else:
+ p.pretty(cls_ctor())
+
+
+def _userlist_pprint(obj, p, cycle):
+ cls_ctor = CallExpression.factory(obj.__class__.__name__)
+ if cycle:
+ p.pretty(cls_ctor(RawText("...")))
+ else:
+ p.pretty(cls_ctor(obj.data))
+
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
for_type_by_name('collections', 'deque', _deque_pprint)
for_type_by_name('collections', 'Counter', _counter_pprint)
+for_type_by_name("collections", "UserList", _userlist_pprint)
if __name__ == '__main__':
from random import randrange
diff --git a/contrib/python/ipython/py3/IPython/lib/security.py b/contrib/python/ipython/py3/IPython/lib/security.py
deleted file mode 100644
index 91a2344eab..0000000000
--- a/contrib/python/ipython/py3/IPython/lib/security.py
+++ /dev/null
@@ -1,114 +0,0 @@
-"""
-Password generation for the IPython notebook.
-"""
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-# Stdlib
-import getpass
-import hashlib
-import random
-
-# Our own
-from IPython.core.error import UsageError
-from IPython.utils.py3compat import encode
-
-#-----------------------------------------------------------------------------
-# Globals
-#-----------------------------------------------------------------------------
-
-# Length of the salt in nr of hex chars, which implies salt_len * 4
-# bits of randomness.
-salt_len = 12
-
-#-----------------------------------------------------------------------------
-# Functions
-#-----------------------------------------------------------------------------
-
-def passwd(passphrase=None, algorithm='sha1'):
- """Generate hashed password and salt for use in notebook configuration.
-
- In the notebook configuration, set `c.NotebookApp.password` to
- the generated string.
-
- Parameters
- ----------
- passphrase : str
- Password to hash. If unspecified, the user is asked to input
- and verify a password.
- algorithm : str
- Hashing algorithm to use (e.g, 'sha1' or any argument supported
- by :func:`hashlib.new`).
-
- Returns
- -------
- hashed_passphrase : str
- Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'.
-
- Examples
- --------
- >>> passwd('mypassword')
- 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12'
-
- """
- if passphrase is None:
- for i in range(3):
- p0 = getpass.getpass('Enter password: ')
- p1 = getpass.getpass('Verify password: ')
- if p0 == p1:
- passphrase = p0
- break
- else:
- print('Passwords do not match.')
- else:
- raise UsageError('No matching passwords found. Giving up.')
-
- h = hashlib.new(algorithm)
- salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
- h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii'))
-
- return ':'.join((algorithm, salt, h.hexdigest()))
-
-
-def passwd_check(hashed_passphrase, passphrase):
- """Verify that a given passphrase matches its hashed version.
-
- Parameters
- ----------
- hashed_passphrase : str
- Hashed password, in the format returned by `passwd`.
- passphrase : str
- Passphrase to validate.
-
- Returns
- -------
- valid : bool
- True if the passphrase matches the hash.
-
- Examples
- --------
- >>> from IPython.lib.security import passwd_check
- >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
- ... 'mypassword')
- True
-
- >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a',
- ... 'anotherpassword')
- False
- """
- try:
- algorithm, salt, pw_digest = hashed_passphrase.split(':', 2)
- except (ValueError, TypeError):
- return False
-
- try:
- h = hashlib.new(algorithm)
- except ValueError:
- return False
-
- if len(pw_digest) == 0:
- return False
-
- h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii'))
-
- return h.hexdigest() == pw_digest