diff options
author | robot-contrib <robot-contrib@yandex-team.ru> | 2022-05-18 00:43:36 +0300 |
---|---|---|
committer | robot-contrib <robot-contrib@yandex-team.ru> | 2022-05-18 00:43:36 +0300 |
commit | 9e5f436a8b2a27bcc7802e443ea3ef3e41a82a75 (patch) | |
tree | 78b522cab9f76336e62064d4d8ff7c897659b20e /contrib/python/ipython/py3/IPython/utils | |
parent | 8113a823ffca6451bb5ff8f0334560885a939a24 (diff) | |
download | ydb-9e5f436a8b2a27bcc7802e443ea3ef3e41a82a75.tar.gz |
Update contrib/python/ipython/py3 to 8.3.0
ref:e84342d4d30476f9148137f37fd0c6405fd36f55
Diffstat (limited to 'contrib/python/ipython/py3/IPython/utils')
29 files changed, 188 insertions, 544 deletions
diff --git a/contrib/python/ipython/py3/IPython/utils/_process_cli.py b/contrib/python/ipython/py3/IPython/utils/_process_cli.py index 89a31c3164..86e918a8d0 100644 --- a/contrib/python/ipython/py3/IPython/utils/_process_cli.py +++ b/contrib/python/ipython/py3/IPython/utils/_process_cli.py @@ -19,17 +19,8 @@ import System import os # Import IPython libraries: -from IPython.utils import py3compat from ._process_common import arg_split -def _find_cmd(cmd): - """Find the full path to a command using which.""" - paths = System.Environment.GetEnvironmentVariable("PATH").Split(os.pathsep) - for path in paths: - filename = os.path.join(path, cmd) - if System.IO.File.Exists(filename): - return py3compat.decode(filename) - raise OSError("command %r not found" % cmd) def system(cmd): """ diff --git a/contrib/python/ipython/py3/IPython/utils/_process_common.py b/contrib/python/ipython/py3/IPython/utils/_process_common.py index 2a647dc7fa..2a0b828839 100644 --- a/contrib/python/ipython/py3/IPython/utils/_process_common.py +++ b/contrib/python/ipython/py3/IPython/utils/_process_common.py @@ -49,18 +49,16 @@ def process_handler(cmd, callback, stderr=subprocess.PIPE): Parameters ---------- cmd : str or list - A command to be executed by the system, using :class:`subprocess.Popen`. - If a string is passed, it will be run in the system shell. If a list is - passed, it will be used directly as arguments. - + A command to be executed by the system, using :class:`subprocess.Popen`. + If a string is passed, it will be run in the system shell. If a list is + passed, it will be used directly as arguments. callback : callable - A one-argument function that will be called with the Popen object. - + A one-argument function that will be called with the Popen object. stderr : file descriptor number, optional - By default this is set to ``subprocess.PIPE``, but you can also pass the - value ``subprocess.STDOUT`` to force the subprocess' stderr to go into - the same file descriptor as its stdout. This is useful to read stdout - and stderr combined in the order they are generated. + By default this is set to ``subprocess.PIPE``, but you can also pass the + value ``subprocess.STDOUT`` to force the subprocess' stderr to go into + the same file descriptor as its stdout. This is useful to read stdout + and stderr combined in the order they are generated. Returns ------- @@ -117,12 +115,12 @@ def getoutput(cmd): Parameters ---------- cmd : str or list - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- output : str - A string containing the combination of stdout and stderr from the + A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descriptors (so the order of the information in this string is the correct order as would be seen if running the command in a terminal). @@ -141,7 +139,7 @@ def getoutputerror(cmd): Parameters ---------- cmd : str or list - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- @@ -159,7 +157,7 @@ def get_output_error_code(cmd): Parameters ---------- cmd : str or list - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- diff --git a/contrib/python/ipython/py3/IPython/utils/_process_posix.py b/contrib/python/ipython/py3/IPython/utils/_process_posix.py index a11cad7697..59b5c23896 100644 --- a/contrib/python/ipython/py3/IPython/utils/_process_posix.py +++ b/contrib/python/ipython/py3/IPython/utils/_process_posix.py @@ -24,21 +24,12 @@ import pexpect # Our own from ._process_common import getoutput, arg_split -from IPython.utils import py3compat from IPython.utils.encoding import DEFAULT_ENCODING #----------------------------------------------------------------------------- # Function definitions #----------------------------------------------------------------------------- -def _find_cmd(cmd): - """Find the full path to a command using which.""" - - path = sp.Popen(['/usr/bin/env', 'which', cmd], - stdout=sp.PIPE, stderr=sp.PIPE).communicate()[0] - return py3compat.decode(path) - - class ProcessHandler(object): """Execute subprocesses under the control of pexpect. """ @@ -82,12 +73,12 @@ class ProcessHandler(object): Parameters ---------- cmd : str - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- output : str - A string containing the combination of stdout and stderr from the + A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descriptors (so the order of the information in this string is the correct order as would be seen if running the command in a terminal). @@ -103,12 +94,12 @@ class ProcessHandler(object): Parameters ---------- cmd : str - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- output : str - A string containing the combination of stdout and stderr from the + A string containing the combination of stdout and stderr from the subprocess, in whatever order the subprocess originally wrote to its file descriptors (so the order of the information in this string is the correct order as would be seen if running the command in a terminal). @@ -124,7 +115,7 @@ class ProcessHandler(object): Parameters ---------- cmd : str - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- diff --git a/contrib/python/ipython/py3/IPython/utils/_process_win32.py b/contrib/python/ipython/py3/IPython/utils/_process_win32.py index 6d05bdaa12..36fb092d7b 100644 --- a/contrib/python/ipython/py3/IPython/utils/_process_win32.py +++ b/contrib/python/ipython/py3/IPython/utils/_process_win32.py @@ -71,27 +71,6 @@ class AvoidUNCPath(object): os.chdir(self.path) -def _find_cmd(cmd): - """Find the full path to a .bat or .exe using the win32api module.""" - try: - from win32api import SearchPath - except ImportError: - raise ImportError('you need to have pywin32 installed for this to work') - else: - PATH = os.environ['PATH'] - extensions = ['.exe', '.com', '.bat', '.py'] - path = None - for ext in extensions: - try: - path = SearchPath(PATH, cmd, ext)[0] - except: - pass - if path is None: - raise OSError("command %r not found" % cmd) - else: - return path - - def _system_body(p): """Callback for _system.""" enc = DEFAULT_ENCODING @@ -128,7 +107,7 @@ def system(cmd): Parameters ---------- cmd : str or list - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- @@ -152,7 +131,7 @@ def getoutput(cmd): Parameters ---------- cmd : str or list - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- @@ -181,7 +160,7 @@ try: This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix parameter is ignored. - + If strict=False, process_common.arg_split(...strict=False) is used instead. """ #CommandLineToArgvW returns path to executable if called with empty string. diff --git a/contrib/python/ipython/py3/IPython/utils/_process_win32_controller.py b/contrib/python/ipython/py3/IPython/utils/_process_win32_controller.py index c2e2329c45..f8c2a057a8 100644 --- a/contrib/python/ipython/py3/IPython/utils/_process_win32_controller.py +++ b/contrib/python/ipython/py3/IPython/utils/_process_win32_controller.py @@ -551,13 +551,13 @@ def system(cmd): Parameters ---------- cmd : str - A command to be executed in the system shell. + A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value - would trigger :func:`sys.displayhook` calls. + would trigger : func:`sys.displayhook` calls. """ with AvoidUNCPath() as path: if path is not None: diff --git a/contrib/python/ipython/py3/IPython/utils/_sysinfo.py b/contrib/python/ipython/py3/IPython/utils/_sysinfo.py index 6c996d02d4..65cb32d0d5 100644 --- a/contrib/python/ipython/py3/IPython/utils/_sysinfo.py +++ b/contrib/python/ipython/py3/IPython/utils/_sysinfo.py @@ -1,2 +1,2 @@ # GENERATED BY setup.py -commit = u"fd4cac190" +commit = u"55e81b920" diff --git a/contrib/python/ipython/py3/IPython/utils/coloransi.py b/contrib/python/ipython/py3/IPython/utils/coloransi.py index bc8e8377f7..e331421802 100644 --- a/contrib/python/ipython/py3/IPython/utils/coloransi.py +++ b/contrib/python/ipython/py3/IPython/utils/coloransi.py @@ -176,9 +176,9 @@ class ColorSchemeTable(dict): scheme_test = scheme.lower() try: scheme_idx = valid_schemes.index(scheme_test) - except ValueError: + except ValueError as e: raise ValueError('Unrecognized color scheme: ' + scheme + \ - '\nValid schemes: '+str(scheme_names).replace("'', ",'')) + '\nValid schemes: '+str(scheme_names).replace("'', ",'')) from e else: active = scheme_names[scheme_idx] self.active_scheme_name = active diff --git a/contrib/python/ipython/py3/IPython/utils/contexts.py b/contrib/python/ipython/py3/IPython/utils/contexts.py index 4d379b0eda..7f95d4419d 100644 --- a/contrib/python/ipython/py3/IPython/utils/contexts.py +++ b/contrib/python/ipython/py3/IPython/utils/contexts.py @@ -58,17 +58,3 @@ class preserve_keys(object): for k in self.to_delete: d.pop(k, None) d.update(self.to_update) - - -class NoOpContext(object): - """ - Deprecated - - Context manager that does nothing.""" - - def __init__(self): - warnings.warn("""NoOpContext is deprecated since IPython 5.0 """, - DeprecationWarning, stacklevel=2) - - def __enter__(self): pass - def __exit__(self, type, value, traceback): pass diff --git a/contrib/python/ipython/py3/IPython/utils/decorators.py b/contrib/python/ipython/py3/IPython/utils/decorators.py index c26485553c..47791d7ca6 100644 --- a/contrib/python/ipython/py3/IPython/utils/decorators.py +++ b/contrib/python/ipython/py3/IPython/utils/decorators.py @@ -50,7 +50,7 @@ def flag_calls(func): def undoc(func): """Mark a function or class as undocumented. - + This is found by inspecting the AST, so for now it must be used directly as @undoc, not as e.g. @decorators.undoc """ diff --git a/contrib/python/ipython/py3/IPython/utils/encoding.py b/contrib/python/ipython/py3/IPython/utils/encoding.py index 69a319ef0e..651ee0c0b5 100644 --- a/contrib/python/ipython/py3/IPython/utils/encoding.py +++ b/contrib/python/ipython/py3/IPython/utils/encoding.py @@ -37,10 +37,10 @@ def get_stream_enc(stream, default=None): # won't need to make changes all over IPython. def getdefaultencoding(prefer_stream=True): """Return IPython's guess for the default encoding for bytes as text. - + If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. - + Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, diff --git a/contrib/python/ipython/py3/IPython/utils/frame.py b/contrib/python/ipython/py3/IPython/utils/frame.py index 74c6d4197f..808906bda8 100644 --- a/contrib/python/ipython/py3/IPython/utils/frame.py +++ b/contrib/python/ipython/py3/IPython/utils/frame.py @@ -28,12 +28,10 @@ def extract_vars(*names,**kw): *names : str One or more variable names which will be extracted from the caller's frame. - - depth : integer, optional + **kw : integer, optional How many frames in the stack to walk when looking for your variables. The default is 0, which will use the frame where the call was made. - Examples -------- :: diff --git a/contrib/python/ipython/py3/IPython/utils/generics.py b/contrib/python/ipython/py3/IPython/utils/generics.py index fcada6f44d..3626ca4cc7 100644 --- a/contrib/python/ipython/py3/IPython/utils/generics.py +++ b/contrib/python/ipython/py3/IPython/utils/generics.py @@ -22,7 +22,6 @@ def complete_object(obj, prev_completions): The object to complete. prev_completions : list List of attributes discovered so far. - This should return the list of attributes in obj. If you only wish to add to the attributes already discovered normally, return own_attrs + prev_completions. diff --git a/contrib/python/ipython/py3/IPython/utils/importstring.py b/contrib/python/ipython/py3/IPython/utils/importstring.py index c8e1840eb3..51bfc7b569 100644 --- a/contrib/python/ipython/py3/IPython/utils/importstring.py +++ b/contrib/python/ipython/py3/IPython/utils/importstring.py @@ -16,12 +16,12 @@ def import_item(name): Parameters ---------- name : string - The fully qualified name of the module/package being imported. + The fully qualified name of the module/package being imported. Returns ------- mod : module object - The module that was imported. + The module that was imported. """ parts = name.rsplit('.', 1) @@ -31,8 +31,8 @@ def import_item(name): module = __import__(package, fromlist=[obj]) try: pak = getattr(module, obj) - except AttributeError: - raise ImportError('No module named %s' % obj) + except AttributeError as e: + raise ImportError('No module named %s' % obj) from e return pak else: # called with un-dotted string diff --git a/contrib/python/ipython/py3/IPython/utils/io.py b/contrib/python/ipython/py3/IPython/utils/io.py index fab9bae797..170bc625ac 100644 --- a/contrib/python/ipython/py3/IPython/utils/io.py +++ b/contrib/python/ipython/py3/IPython/utils/io.py @@ -13,87 +13,16 @@ import os import sys import tempfile import warnings +from pathlib import Path from warnings import warn from IPython.utils.decorators import undoc from .capture import CapturedIO, capture_output -@undoc -class IOStream: - - def __init__(self, stream, fallback=None): - warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead', - DeprecationWarning, stacklevel=2) - if not hasattr(stream,'write') or not hasattr(stream,'flush'): - if fallback is not None: - stream = fallback - else: - raise ValueError("fallback required, but not specified") - self.stream = stream - self._swrite = stream.write - - # clone all methods not overridden: - 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) - - def __repr__(self): - cls = self.__class__ - tpl = '{mod}.{cls}({args})' - return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream) - - def write(self,data): - warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead', - DeprecationWarning, stacklevel=2) - try: - self._swrite(data) - except: - try: - # print handles some unicode issues which may trip a plain - # write() call. Emulate write() by using an empty end - # argument. - print(data, end='', file=self.stream) - except: - # if we get here, something is seriously broken. - print('ERROR - failed to write data to stream:', self.stream, - file=sys.stderr) - - def writelines(self, lines): - warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead', - DeprecationWarning, stacklevel=2) - if isinstance(lines, str): - lines = [lines] - for line in lines: - self.write(line) - - # This class used to have a writeln method, but regular files and streams - # in Python don't have this method. We need to keep this completely - # compatible so we removed it. - - @property - def closed(self): - return self.stream.closed - - def close(self): - pass - # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr -devnull = open(os.devnull, 'w') +devnull = open(os.devnull, "w", encoding="utf-8") atexit.register(devnull.close) -# io.std* are deprecated, but don't show our own deprecation warnings -# during initialization of the deprecated API. -with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - stdin = IOStream(sys.stdin, fallback=devnull) - stdout = IOStream(sys.stdout, fallback=devnull) - stderr = IOStream(sys.stderr, fallback=devnull) class Tee(object): """A class to duplicate an output stream to stdout/err. @@ -112,11 +41,9 @@ class Tee(object): Parameters ---------- file_or_name : filename or open filehandle (writable) - File that will be duplicated - + File that will be duplicated mode : optional, valid mode for open(). - If a filename was give, open with this mode. - + If a filename was give, open with this mode. channel : str, one of ['stdout', 'stderr'] """ if channel not in ['stdout', 'stderr']: @@ -125,7 +52,8 @@ class Tee(object): if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'): self.file = file_or_name else: - self.file = open(file_or_name, mode) + encoding = None if "b" in mode else "utf-8" + self.file = open(file_or_name, mode, encoding=encoding) self.channel = channel self.ostream = getattr(sys, channel) setattr(sys, channel, self) @@ -194,28 +122,21 @@ def temp_pyfile(src, ext='.py'): Parameters ---------- src : string or list of strings (no need for ending newlines if list) - Source code to be written to the file. - + Source code to be written to the file. ext : optional, string - Extension for the generated file. + Extension for the generated file. Returns ------- (filename, open filehandle) - It is the caller's responsibility to close the open file and unlink it. + It is the caller's responsibility to close the open file and unlink it. """ fname = tempfile.mkstemp(ext)[1] - with open(fname,'w') as f: + with open(Path(fname), "w", encoding="utf-8") as f: f.write(src) f.flush() return fname -@undoc -def atomic_writing(*args, **kwargs): - """DEPRECATED: moved to notebook.services.contents.fileio""" - warn("IPython.utils.io.atomic_writing has moved to notebook.services.contents.fileio since IPython 4.0", DeprecationWarning, stacklevel=2) - from notebook.services.contents.fileio import atomic_writing - return atomic_writing(*args, **kwargs) @undoc def raw_print(*args, **kw): @@ -234,15 +155,3 @@ def raw_print_err(*args, **kw): print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), file=sys.__stderr__) sys.__stderr__.flush() - -# used by IPykernel <- 4.9. Removed during IPython 7-dev period and re-added -# Keep for a version or two then should remove -rprint = raw_print -rprinte = raw_print_err - -@undoc -def unicode_std_stream(stream='stdout'): - """DEPRECATED, moved to nbconvert.utils.io""" - warn("IPython.utils.io.unicode_std_stream has moved to nbconvert.utils.io since IPython 4.0", DeprecationWarning, stacklevel=2) - from nbconvert.utils.io import unicode_std_stream - return unicode_std_stream(stream) diff --git a/contrib/python/ipython/py3/IPython/utils/ipstruct.py b/contrib/python/ipython/py3/IPython/utils/ipstruct.py index e2b3e8fa4c..ed112101a3 100644 --- a/contrib/python/ipython/py3/IPython/utils/ipstruct.py +++ b/contrib/python/ipython/py3/IPython/utils/ipstruct.py @@ -43,14 +43,13 @@ class Struct(dict): Parameters ---------- - args : dict, Struct + *args : dict, Struct Initialize with one dict or Struct - kw : dict + **kw : dict Initialize with key, value pairs. Examples -------- - >>> s = Struct(a=10,b=30) >>> s.a 10 @@ -68,7 +67,6 @@ class Struct(dict): Examples -------- - >>> s = Struct() >>> s['a'] = 10 >>> s.allow_new_attr(False) @@ -95,7 +93,6 @@ class Struct(dict): Examples -------- - >>> s = Struct() >>> s.a = 10 >>> s.a @@ -120,7 +117,7 @@ class Struct(dict): try: self.__setitem__(key, value) except KeyError as e: - raise AttributeError(e) + raise AttributeError(e) from e def __getattr__(self, key): """Get an attr by calling :meth:`dict.__getitem__`. @@ -130,12 +127,11 @@ class Struct(dict): Examples -------- - >>> s = Struct(a=10) >>> s.a 10 >>> type(s.get) - <... 'builtin_function_or_method'> + <...method'> >>> try: ... s.b ... except AttributeError: @@ -145,8 +141,8 @@ class Struct(dict): """ try: result = self[key] - except KeyError: - raise AttributeError(key) + except KeyError as e: + raise AttributeError(key) from e else: return result @@ -155,7 +151,6 @@ class Struct(dict): Examples -------- - >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s += s2 @@ -170,7 +165,6 @@ class Struct(dict): Examples -------- - >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s = s1 + s2 @@ -186,7 +180,6 @@ class Struct(dict): Examples -------- - >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s = s1 - s2 @@ -202,7 +195,6 @@ class Struct(dict): Examples -------- - >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s1 -= s2 @@ -236,7 +228,6 @@ class Struct(dict): Examples -------- - >>> s = Struct(a=10,b=30) >>> s2 = s.copy() >>> type(s2) is Struct @@ -251,7 +242,6 @@ class Struct(dict): Examples -------- - >>> s = Struct(a=10) >>> s.hasattr('a') True @@ -284,7 +274,7 @@ class Struct(dict): Parameters ---------- - __loc_data : dict, Struct + __loc_data__ : dict, Struct The data to merge into self __conflict_solve : dict The conflict policy dict. The keys are binary functions used to @@ -292,12 +282,11 @@ class Struct(dict): the keys the conflict resolution function applies to. Instead of a list of strings a space separated string can be used, like 'a b c'. - kw : dict + **kw : dict Additional key, value pairs to merge in Notes ----- - The `__conflict_solve` dict is a dictionary of binary functions which will be used to solve key conflicts. Here is an example:: @@ -338,7 +327,6 @@ class Struct(dict): Examples -------- - This show the default policy: >>> s = Struct(a=10,b=30) diff --git a/contrib/python/ipython/py3/IPython/utils/module_paths.py b/contrib/python/ipython/py3/IPython/utils/module_paths.py index 0570c322e6..f9f7cacc33 100644 --- a/contrib/python/ipython/py3/IPython/utils/module_paths.py +++ b/contrib/python/ipython/py3/IPython/utils/module_paths.py @@ -2,8 +2,6 @@ Utility functions for finding modules on sys.path. -`find_module` returns a path to module or None, given certain conditions. - """ #----------------------------------------------------------------------------- # Copyright (c) 2011, the IPython Development Team. @@ -20,6 +18,7 @@ Utility functions for finding modules on sys.path. # Stdlib imports import importlib import os +import sys # Third-party imports @@ -42,7 +41,7 @@ def find_mod(module_name): """ Find module `module_name` on sys.path, and return the path to module `module_name`. - - If `module_name` refers to a module directory, then return path to __init__ file. + - If `module_name` refers to a module directory, then return path to __init__ file. - If `module_name` is a directory without an __init__file, return None. - If module is missing or does not have a `.py` or `.pyw` extension, return None. - Note that we are not interested in running bytecode. @@ -51,16 +50,18 @@ def find_mod(module_name): Parameters ---------- module_name : str - + Returns ------- module_path : str Path to module `module_name`, its __init__.py, or None, depending on above conditions. """ - loader = importlib.util.find_spec(module_name) - module_path = loader.origin + spec = importlib.util.find_spec(module_name) + module_path = spec.origin if module_path is None: + if spec.loader in sys.meta_path: + return spec.loader return None else: split_path = module_path.split(".") diff --git a/contrib/python/ipython/py3/IPython/utils/openpy.py b/contrib/python/ipython/py3/IPython/utils/openpy.py index c90d2b53a3..297a762c7d 100644 --- a/contrib/python/ipython/py3/IPython/utils/openpy.py +++ b/contrib/python/ipython/py3/IPython/utils/openpy.py @@ -7,6 +7,7 @@ Much of the code is taken from the tokenize module in Python 3.2. import io from io import TextIOWrapper, BytesIO +from pathlib import Path import re from tokenize import open, detect_encoding @@ -59,20 +60,21 @@ def strip_encoding_cookie(filelike): def read_py_file(filename, skip_encoding_cookie=True): """Read a Python file, using the encoding declared inside the file. - + Parameters ---------- filename : str - The path to the file to read. + The path to the file to read. skip_encoding_cookie : bool - If True (the default), and the encoding declaration is found in the first - two lines, that line will be excluded from the output. - + If True (the default), and the encoding declaration is found in the first + two lines, that line will be excluded from the output. + Returns ------- A unicode string containing the contents of the file. """ - with open(filename) as f: # the open function defined in this module. + filepath = Path(filename) + with open(filepath) as f: # the open function defined in this module. if skip_encoding_cookie: return "".join(strip_encoding_cookie(f)) else: @@ -80,18 +82,18 @@ def read_py_file(filename, skip_encoding_cookie=True): def read_py_url(url, errors='replace', skip_encoding_cookie=True): """Read a Python file from a URL, using the encoding declared inside the file. - + Parameters ---------- url : str - The URL from which to fetch the file. + The URL from which to fetch the file. errors : str - How to handle decoding errors in the file. Options are the same as for - bytes.decode(), but here 'replace' is the default. + How to handle decoding errors in the file. Options are the same as for + bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool - If True (the default), and the encoding declaration is found in the first - two lines, that line will be excluded from the output. - + If True (the default), and the encoding declaration is found in the first + two lines, that line will be excluded from the output. + Returns ------- A unicode string containing the contents of the file. diff --git a/contrib/python/ipython/py3/IPython/utils/path.py b/contrib/python/ipython/py3/IPython/utils/path.py index 0fb6144e19..3db33e4c43 100644 --- a/contrib/python/ipython/py3/IPython/utils/path.py +++ b/contrib/python/ipython/py3/IPython/utils/path.py @@ -33,14 +33,14 @@ if sys.platform == 'win32': Examples -------- - >>> get_long_path_name('c:\\docume~1') + >>> get_long_path_name('c:\\\\docume~1') 'c:\\\\Documents and Settings' """ try: import ctypes - except ImportError: - raise ImportError('you need to have ctypes installed for this to work') + except ImportError as e: + raise ImportError('you need to have ctypes installed for this to work') from e _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint ] @@ -67,20 +67,6 @@ def get_long_path_name(path): return _get_long_path_name(path) -def unquote_filename(name, win32=(sys.platform=='win32')): - """ On Windows, remove leading and trailing quotes from filenames. - - This function has been deprecated and should not be used any more: - 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) - if win32: - if name.startswith(("'", '"')) and name.endswith(("'", '"')): - name = name[1:-1] - return name - - def compress_user(path): """Reverse of :func:`os.path.expanduser` """ @@ -89,7 +75,7 @@ def compress_user(path): path = "~" + path[len(home):] return path -def get_py_filename(name, force_win32=None): +def get_py_filename(name): """Return a valid python filename in the current directory. If the given name is not a file, it adds '.py' and searches again. @@ -97,10 +83,6 @@ def get_py_filename(name, force_win32=None): """ name = os.path.expanduser(name) - 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) if not os.path.isfile(name) and not name.endswith('.py'): name += '.py' if os.path.isfile(name): @@ -109,7 +91,7 @@ def get_py_filename(name, force_win32=None): raise IOError('File `%r` not found.' % name) -def filefind(filename, path_dirs=None): +def filefind(filename: str, path_dirs=None) -> str: """Find a file by looking through a sequence of paths. This iterates through a sequence of paths looking for a file and returns @@ -139,7 +121,12 @@ def filefind(filename, path_dirs=None): Returns ------- - Raises :exc:`IOError` or returns absolute path to file. + path : str + returns absolute path to file. + + Raises + ------ + IOError """ # If paths are quoted, abspath gets confused, strip them... @@ -178,7 +165,6 @@ def get_home_dir(require_writable=False) -> str: Parameters ---------- - require_writable : bool [default: False] if True: guarantees the return value is a writable directory, otherwise @@ -205,7 +191,7 @@ def get_home_dir(require_writable=False) -> str: pass if (not require_writable) or _writable_dir(homedir): - assert isinstance(homedir, str), "Homedir shoudl be unicode not bytes" + assert isinstance(homedir, str), "Homedir should be unicode not bytes" return homedir else: raise HomeDirError('%s is not a writable dir, ' @@ -219,7 +205,7 @@ def get_xdg_dir(): env = os.environ - if os.name == 'posix' and sys.platform != 'darwin': + if os.name == "posix": # Linux, Unix, AIX, etc. # use ~/.config if empty OR not set xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') @@ -238,7 +224,7 @@ def get_xdg_cache_dir(): env = os.environ - if os.name == 'posix' and sys.platform != 'darwin': + if os.name == "posix": # Linux, Unix, AIX, etc. # use ~/.cache if empty OR not set xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache') @@ -249,36 +235,6 @@ def get_xdg_cache_dir(): return None -@undoc -def get_ipython_dir(): - warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", DeprecationWarning, 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.", DeprecationWarning, 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.", DeprecationWarning, 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.", DeprecationWarning, 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.", DeprecationWarning, stacklevel=2) - from IPython.paths import locate_profile - return locate_profile(profile=profile) - def expand_path(s): """Expand $VARS and ~names in a string, like a shell diff --git a/contrib/python/ipython/py3/IPython/utils/pickleutil.py b/contrib/python/ipython/py3/IPython/utils/pickleutil.py deleted file mode 100644 index 785e6f6c80..0000000000 --- a/contrib/python/ipython/py3/IPython/utils/pickleutil.py +++ /dev/null @@ -1,5 +0,0 @@ -from warnings import warn - -warn("IPython.utils.pickleutil has moved to ipykernel.pickleutil", stacklevel=2) - -from ipykernel.pickleutil import * diff --git a/contrib/python/ipython/py3/IPython/utils/py3compat.py b/contrib/python/ipython/py3/IPython/utils/py3compat.py index c758787300..34af4c58f4 100644 --- a/contrib/python/ipython/py3/IPython/utils/py3compat.py +++ b/contrib/python/ipython/py3/IPython/utils/py3compat.py @@ -3,13 +3,8 @@ This file is deprecated and will be removed in a future version. """ -import functools -import os -import sys -import re -import shutil -import types import platform +import builtins as builtin_mod from .encoding import DEFAULT_ENCODING @@ -18,6 +13,7 @@ def decode(s, encoding=None): encoding = encoding or DEFAULT_ENCODING return s.decode(encoding, "replace") + def encode(u, encoding=None): encoding = encoding or DEFAULT_ENCODING return u.encode(encoding, "replace") @@ -28,36 +24,6 @@ def cast_unicode(s, encoding=None): return decode(s, encoding) return s -def cast_bytes(s, encoding=None): - if not isinstance(s, bytes): - return encode(s, encoding) - return s - -def buffer_to_bytes(buf): - """Cast a buffer object to bytes""" - if not isinstance(buf, bytes): - buf = bytes(buf) - return buf - -def _modify_str_or_docstring(str_change_func): - @functools.wraps(str_change_func) - def wrapper(func_or_str): - if isinstance(func_or_str, (str,)): - func = None - doc = func_or_str - else: - func = func_or_str - doc = func.__doc__ - - # PYTHONOPTIMIZE=2 strips docstrings, so they can disappear unexpectedly - if doc is not None: - doc = str_change_func(doc) - - if func: - func.__doc__ = doc - return func - return doc - return wrapper def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be @@ -73,119 +39,29 @@ def safe_unicode(e): except UnicodeError: pass - return u'Unrecoverably corrupt evalue' - -# shutil.which from Python 3.4 -def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): - """Given a command, mode, and a PATH string, return the path which - conforms to the given mode on the PATH, or None if there is no such - file. + return "Unrecoverably corrupt evalue" - `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result - of os.environ.get("PATH"), or can be overridden with a custom search - path. - - This is a backport of shutil.which from Python 3.4 - """ - # Check that a given file can be accessed with the correct mode. - # Additionally check that `file` is not a directory, as on Windows - # directories pass the os.access check. - def _access_check(fn, mode): - return (os.path.exists(fn) and os.access(fn, mode) - and not os.path.isdir(fn)) - - # If we're given a path with a directory part, look it up directly rather - # than referring to PATH directories. This includes checking relative to the - # current directory, e.g. ./script - if os.path.dirname(cmd): - if _access_check(cmd, mode): - return cmd - return None - - if path is None: - path = os.environ.get("PATH", os.defpath) - if not path: - return None - path = path.split(os.pathsep) - - if sys.platform == "win32": - # The current directory takes precedence on Windows. - if not os.curdir in path: - path.insert(0, os.curdir) - - # PATHEXT is necessary to check on Windows. - pathext = os.environ.get("PATHEXT", "").split(os.pathsep) - # See if the given file matches any of the expected path extensions. - # This will allow us to short circuit when given "python.exe". - # If it does match, only test that one, otherwise we have to try - # others. - if any(cmd.lower().endswith(ext.lower()) for ext in pathext): - files = [cmd] - else: - files = [cmd + ext for ext in pathext] - else: - # On other platforms you don't have things like PATHEXT to tell you - # what file suffixes are executable, so just pass on cmd as-is. - files = [cmd] - - seen = set() - for dir in path: - normdir = os.path.normcase(dir) - if not normdir in seen: - seen.add(normdir) - for thefile in files: - name = os.path.join(dir, thefile) - if _access_check(name, mode): - return name - return None - -PY3 = True # keep reference to builtin_mod because the kernel overrides that value # to forward requests to a frontend. -def input(prompt=''): +def input(prompt=""): return builtin_mod.input(prompt) -builtin_mod_name = "builtins" -import builtins as builtin_mod - - -which = shutil.which - -def isidentifier(s, dotted=False): - if dotted: - return all(isidentifier(a) for a in s.split(".")) - return s.isidentifier() - -getcwd = os.getcwd - -MethodType = types.MethodType def execfile(fname, glob, loc=None, compiler=None): loc = loc if (loc is not None) else glob - with open(fname, 'rb') as f: + with open(fname, "rb") as f: compiler = compiler or compile - exec(compiler(f.read(), fname, 'exec'), glob, loc) - -# Refactor print statements in doctests. -_print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) - -# Abstract u'abc' syntax: -@_modify_str_or_docstring -def u_format(s): - """"{u}'abc'" --> "'abc'" (Python 3) + exec(compiler(f.read(), fname, "exec"), glob, loc) - Accepts a string or a function, so it can be used as a decorator.""" - return s.format(u='') - -PY2 = not PY3 PYPY = platform.python_implementation() == "PyPy" # Cython still rely on that as a Dec 28 2019 # See https://github.com/cython/cython/pull/3291 and # https://github.com/ipython/ipython/issues/12068 def no_code(x, encoding=None): - return x -unicode_to_str = cast_bytes_py2 = no_code + return x + +unicode_to_str = cast_bytes_py2 = no_code diff --git a/contrib/python/ipython/py3/IPython/utils/shimmodule.py b/contrib/python/ipython/py3/IPython/utils/shimmodule.py index b70ac135bf..8af44caa98 100644 --- a/contrib/python/ipython/py3/IPython/utils/shimmodule.py +++ b/contrib/python/ipython/py3/IPython/utils/shimmodule.py @@ -3,6 +3,8 @@ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. +import importlib.abc +import importlib.util import sys import types from importlib import import_module @@ -13,41 +15,26 @@ from .importstring import import_item class ShimWarning(Warning): """A warning to show when a module has moved, and a shim is in its place.""" -class ShimImporter(object): + +class ShimImporter(importlib.abc.MetaPathFinder): """Import hook for a shim. - + This ensures that submodule imports return the real target module, not a clone that will confuse `is` and `isinstance` checks. """ def __init__(self, src, mirror): self.src = src self.mirror = mirror - + def _mirror_name(self, fullname): """get the name of the mirrored module""" - - return self.mirror + fullname[len(self.src):] - def find_module(self, fullname, path=None): - """Return self if we should be used to import the module.""" - if fullname.startswith(self.src + '.'): - mirror_name = self._mirror_name(fullname) - try: - mod = import_item(mirror_name) - except ImportError: - return - else: - if not isinstance(mod, types.ModuleType): - # not a module - return None - return self + return self.mirror + fullname[len(self.src) :] - def load_module(self, fullname): - """Import the mirrored module, and insert it into sys.modules""" - mirror_name = self._mirror_name(fullname) - mod = import_item(mirror_name) - sys.modules[fullname] = mod - return mod + def find_spec(self, fullname, path, target=None): + if fullname.startswith(self.src + "."): + mirror_name = self._mirror_name(fullname) + return importlib.util.find_spec(mirror_name) class ShimModule(types.ModuleType): @@ -90,5 +77,13 @@ class ShimModule(types.ModuleType): name = "%s.%s" % (self._mirror, key) try: return import_item(name) - except ImportError: - raise AttributeError(key) + except ImportError as e: + raise AttributeError(key) from e + + def __repr__(self): + # repr on a module can be called during error handling; make sure + # it does not fail, even if the import fails + try: + return self.__getattr__("__repr__")() + except AttributeError: + return f"<ShimModule for {self._mirror!r}>" diff --git a/contrib/python/ipython/py3/IPython/utils/sysinfo.py b/contrib/python/ipython/py3/IPython/utils/sysinfo.py index 07d14fd8a4..857f0cf2d8 100644 --- a/contrib/python/ipython/py3/IPython/utils/sysinfo.py +++ b/contrib/python/ipython/py3/IPython/utils/sysinfo.py @@ -40,15 +40,15 @@ def pkg_commit_hash(pkg_path): Parameters ---------- pkg_path : str - directory containing package - only used for getting commit from active repo + directory containing package + only used for getting commit from active repo Returns ------- hash_from : str - Where we got the hash from - description + Where we got the hash from - description hash_str : str - short form of hash + short form of hash """ # Try and get commit from written commit text file if _sysinfo.commit: @@ -71,12 +71,12 @@ def pkg_info(pkg_path): Parameters ---------- pkg_path : str - path containing __init__.py for package + path containing __init__.py for package Returns ------- context : dict - with named parameters of interest + with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) return dict( @@ -118,49 +118,25 @@ def sys_info(): """ return pprint.pformat(get_sys_info()) -def _num_cpus_unix(): - """Return the number of active CPUs on a Unix system.""" - return os.sysconf("SC_NPROCESSORS_ONLN") - - -def _num_cpus_darwin(): - """Return the number of active CPUs on a Darwin system.""" - p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) - return p.stdout.read() - - -def _num_cpus_windows(): - """Return the number of active CPUs on a Windows system.""" - return os.environ.get("NUMBER_OF_PROCESSORS") - def num_cpus(): - """Return the effective number of CPUs in the system as an integer. - - This cross-platform function makes an attempt at finding the total number of - available CPUs in the system, as returned by various underlying system and - python calls. + """DEPRECATED - If it can't find a sensible answer, it returns 1 (though an error *may* make - it return a large positive number that's actually incorrect). - """ + Return the effective number of CPUs in the system as an integer. - # Many thanks to the Parallel Python project (http://www.parallelpython.com) - # for the names of the keys we needed to look up for this function. This - # code was inspired by their equivalent function. + This cross-platform function makes an attempt at finding the total number of + available CPUs in the system, as returned by various underlying system and + python calls. - ncpufuncs = {'Linux':_num_cpus_unix, - 'Darwin':_num_cpus_darwin, - 'Windows':_num_cpus_windows - } - - ncpufunc = ncpufuncs.get(platform.system(), - # default to unix version (Solaris, AIX, etc) - _num_cpus_unix) + If it can't find a sensible answer, it returns 1 (though an error *may* make + it return a large positive number that's actually incorrect). + """ + import warnings - try: - ncpus = max(1,int(ncpufunc())) - except: - ncpus = 1 - return ncpus + warnings.warn( + "`num_cpus` is deprecated since IPython 8.0. Use `os.cpu_count` instead.", + DeprecationWarning, + stacklevel=2, + ) + return os.cpu_count() or 1 diff --git a/contrib/python/ipython/py3/IPython/utils/syspathcontext.py b/contrib/python/ipython/py3/IPython/utils/syspathcontext.py index bd1c51500d..7af1ab60af 100644 --- a/contrib/python/ipython/py3/IPython/utils/syspathcontext.py +++ b/contrib/python/ipython/py3/IPython/utils/syspathcontext.py @@ -15,12 +15,21 @@ Authors: #----------------------------------------------------------------------------- import sys +import warnings class appended_to_syspath(object): - """A context for appending a directory to sys.path for a second.""" + """ + Deprecated since IPython 8.1, no replacements. + + A context for appending a directory to sys.path for a second.""" def __init__(self, dir): + warnings.warn( + "`appended_to_syspath` is deprecated since IPython 8.1, and has no replacements", + DeprecationWarning, + stacklevel=2, + ) self.dir = dir def __enter__(self): diff --git a/contrib/python/ipython/py3/IPython/utils/tempdir.py b/contrib/python/ipython/py3/IPython/utils/tempdir.py index 98f6aeb3c6..5afc5d6425 100644 --- a/contrib/python/ipython/py3/IPython/utils/tempdir.py +++ b/contrib/python/ipython/py3/IPython/utils/tempdir.py @@ -5,12 +5,12 @@ creating a context manager for the working directory which is also temporary. """ import os as _os +from pathlib import Path from tempfile import TemporaryDirectory class NamedFileInTemporaryDirectory(object): - - def __init__(self, filename, mode='w+b', bufsize=-1, **kwds): + def __init__(self, filename, mode="w+b", bufsize=-1, add_to_syspath=False, **kwds): """ Open a file named `filename` in a temporary directory. @@ -22,8 +22,9 @@ class NamedFileInTemporaryDirectory(object): """ self._tmpdir = TemporaryDirectory(**kwds) - path = _os.path.join(self._tmpdir.name, filename) - self.file = open(path, mode, bufsize) + path = Path(self._tmpdir.name) / filename + encoding = None if "b" in mode else "utf-8" + self.file = open(path, mode, bufsize, encoding=encoding) def cleanup(self): self.file.close() @@ -48,7 +49,7 @@ class TemporaryWorkingDirectory(TemporaryDirectory): ... """ def __enter__(self): - self.old_wd = _os.getcwd() + self.old_wd = Path.cwd() _os.chdir(self.name) return super(TemporaryWorkingDirectory, self).__enter__() diff --git a/contrib/python/ipython/py3/IPython/utils/terminal.py b/contrib/python/ipython/py3/IPython/utils/terminal.py index 4e1800208c..49fd3fe173 100644 --- a/contrib/python/ipython/py3/IPython/utils/terminal.py +++ b/contrib/python/ipython/py3/IPython/utils/terminal.py @@ -45,7 +45,7 @@ def toggle_set_term_title(val): Parameters ---------- - val : bool + val : bool If True, set_term_title() actually writes to the terminal (using the appropriate platform-specific module). If False, it is a no-op. """ diff --git a/contrib/python/ipython/py3/IPython/utils/text.py b/contrib/python/ipython/py3/IPython/utils/text.py index 256fdab584..74bccddf68 100644 --- a/contrib/python/ipython/py3/IPython/utils/text.py +++ b/contrib/python/ipython/py3/IPython/utils/text.py @@ -16,7 +16,6 @@ import textwrap from string import Formatter from pathlib import Path -from IPython.utils import py3compat # datetime.strftime date format for ipython if sys.platform == 'win32': @@ -254,7 +253,6 @@ def indent(instr,nspaces=4, ntabs=0, flatten=False): Parameters ---------- - instr : basestring The string to be indented. nspaces : int (default: 4) @@ -268,7 +266,6 @@ def indent(instr,nspaces=4, ntabs=0, flatten=False): Returns ------- - str|unicode : string indented by ntabs and nspaces. """ @@ -392,7 +389,6 @@ def wrap_paragraphs(text, ncols=80): Returns ------- - list of complete paragraphs, wrapped to fill `ncols` columns. """ paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) @@ -463,7 +459,7 @@ def strip_email_quotes(text): def strip_ansi(source): """ Remove ansi escape codes from text. - + Parameters ---------- source : str @@ -474,11 +470,11 @@ def strip_ansi(source): class EvalFormatter(Formatter): """A String Formatter that allows evaluation of simple expressions. - - Note that this version interprets a : as specifying a format string (as per + + Note that this version interprets a `:` as specifying a format string (as per standard string formatting), so if slicing is required, you must explicitly create a slice. - + This is to be used in templating cases, such as the parallel batch script templates, where simple arithmetic on arguments is useful. @@ -643,7 +639,6 @@ def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) : Parameters ---------- - items list of strings to columize row_first : (default False) @@ -658,14 +653,11 @@ def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) : Returns ------- - strings_matrix - nested list of string, the outer most list contains as many list as rows, the innermost lists have each as many element as columns. If the total number of elements in `items` does not equal the product of rows*columns, the last element of some lists are filled with `None`. - dict_info some info to make columnize easier: @@ -698,21 +690,18 @@ def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) : return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info) -def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False): - """ Transform a list of strings into a single string with columns. +def columnize(items, row_first=False, separator=" ", displaywidth=80, spread=False): + """Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. - row_first : (default False) Whether to compute columns for a row-first matrix instead of column-first (default). - separator : str, optional [default is two spaces] The string that separates columns. - displaywidth : int, optional [default is 80] Width of the display in number of characters. diff --git a/contrib/python/ipython/py3/IPython/utils/timing.py b/contrib/python/ipython/py3/IPython/utils/timing.py index 92f6883c4a..3a181ae728 100644 --- a/contrib/python/ipython/py3/IPython/utils/timing.py +++ b/contrib/python/ipython/py3/IPython/utils/timing.py @@ -64,13 +64,14 @@ if resource is not None and hasattr(resource, "getrusage"): else: # There is no distinction of user/system time under windows, so we just use - # time.perff_counter() for everything... - clocku = clocks = clock = time.perf_counter + # time.process_time() for everything... + clocku = clocks = clock = time.process_time + def clock2(): """Under windows, system CPU time can't be measured. - This just returns perf_counter() and zero.""" - return time.perf_counter(),0.0 + This just returns process_time() and zero.""" + return time.process_time(), 0.0 def timings_out(reps,func,*args,**kw): diff --git a/contrib/python/ipython/py3/IPython/utils/tokenutil.py b/contrib/python/ipython/py3/IPython/utils/tokenutil.py index 28f8b6d526..697d2b504a 100644 --- a/contrib/python/ipython/py3/IPython/utils/tokenutil.py +++ b/contrib/python/ipython/py3/IPython/utils/tokenutil.py @@ -23,20 +23,18 @@ def generate_tokens(readline): def line_at_cursor(cell, cursor_pos=0): """Return the line in a cell at a given cursor position - + Used for calling line-based APIs that don't support multi-line input, yet. - + Parameters ---------- - - cell: str + cell : str multiline block of text - cursor_pos: integer + cursor_pos : integer the cursor position - + Returns ------- - (line, offset): (string, integer) The line with the current cursor, and the character offset of the start of the line. """ @@ -58,15 +56,14 @@ def line_at_cursor(cell, cursor_pos=0): def token_at_cursor(cell, cursor_pos=0): """Get the token at a given cursor - + Used for introspection. - + Function calls are prioritized, so the token for the callable will be returned if the cursor is anywhere inside the call. - + Parameters ---------- - cell : unicode A block of Python code cursor_pos : int diff --git a/contrib/python/ipython/py3/IPython/utils/version.py b/contrib/python/ipython/py3/IPython/utils/version.py index 1de0047e6b..8c65c78e15 100644 --- a/contrib/python/ipython/py3/IPython/utils/version.py +++ b/contrib/python/ipython/py3/IPython/utils/version.py @@ -12,15 +12,13 @@ It is a bit ridiculous that we need these. # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- +from warnings import warn -from distutils.version import LooseVersion +warn( + "The `IPython.utils.version` module has been deprecated since IPython 8.0.", + DeprecationWarning, +) -#----------------------------------------------------------------------------- -# Code -#----------------------------------------------------------------------------- def check_version(v, check): """check version string v >= check @@ -29,6 +27,15 @@ def check_version(v, check): it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. """ + warn( + "`check_version` function is deprecated as of IPython 8.0" + "and will be removed in future versions.", + DeprecationWarning, + stacklevel=2, + ) + + from distutils.version import LooseVersion + try: return LooseVersion(v) >= LooseVersion(check) except TypeError: |