diff options
author | robot-piglet <robot-piglet@yandex-team.com> | 2024-11-09 12:07:32 +0300 |
---|---|---|
committer | robot-piglet <robot-piglet@yandex-team.com> | 2024-11-09 12:17:11 +0300 |
commit | 381a9a45520ba56577e90032e086e0168a03b956 (patch) | |
tree | f49a7f9feff6df2c4916cf20205e9c22cb26dfd2 /contrib/python/ipython | |
parent | 66839121782766f516d9a33982e1968d319e3395 (diff) | |
download | ydb-381a9a45520ba56577e90032e086e0168a03b956.tar.gz |
Intermediate changes
commit_hash:2e32c346f257520a6c3629b88dc628744d3d3386
Diffstat (limited to 'contrib/python/ipython')
25 files changed, 275 insertions, 115 deletions
diff --git a/contrib/python/ipython/py3/.dist-info/METADATA b/contrib/python/ipython/py3/.dist-info/METADATA index b3a405d51d..c1f48dd50c 100644 --- a/contrib/python/ipython/py3/.dist-info/METADATA +++ b/contrib/python/ipython/py3/.dist-info/METADATA @@ -1,6 +1,6 @@ Metadata-Version: 2.1 Name: ipython -Version: 8.28.0 +Version: 8.29.0 Summary: IPython: Productive Interactive Computing Author: The IPython Development Team Author-email: ipython-dev@python.org diff --git a/contrib/python/ipython/py3/IPython/core/completer.py b/contrib/python/ipython/py3/IPython/core/completer.py index c639ce07a1..8f843dd584 100644 --- a/contrib/python/ipython/py3/IPython/core/completer.py +++ b/contrib/python/ipython/py3/IPython/core/completer.py @@ -159,7 +159,7 @@ By default results from all matchers are combined, in the order determined by their priority. Matchers can request to suppress results from subsequent matchers by setting ``suppress`` to ``True`` in the ``MatcherResult``. -When multiple matchers simultaneously request surpression, the results from of +When multiple matchers simultaneously request suppression, the results from of the matcher with higher priority will be returned. Sometimes it is desirable to suppress most but not all other matchers; @@ -2652,7 +2652,7 @@ class IPCompleter(Completer): ) can_close_quote = can_close_quote and self.auto_close_dict_keys - # fast path if closing qoute should be appended but not suffix is allowed + # fast path if closing quote should be appended but not suffix is allowed if not can_close_quote and not can_close_bracket and closing_quote: return [leading + k for k in matches] diff --git a/contrib/python/ipython/py3/IPython/core/completerlib.py b/contrib/python/ipython/py3/IPython/core/completerlib.py index 05f39e5015..4612b326de 100644 --- a/contrib/python/ipython/py3/IPython/core/completerlib.py +++ b/contrib/python/ipython/py3/IPython/core/completerlib.py @@ -214,7 +214,7 @@ def is_possible_submodule(module, attr): try: obj = getattr(module, attr) except AttributeError: - # Is possilby an unimported submodule + # Is possibly an unimported submodule return True except TypeError: # https://github.com/ipython/ipython/issues/9678 diff --git a/contrib/python/ipython/py3/IPython/core/debugger.py b/contrib/python/ipython/py3/IPython/core/debugger.py index e7a0b8fb55..84d3de8c5b 100644 --- a/contrib/python/ipython/py3/IPython/core/debugger.py +++ b/contrib/python/ipython/py3/IPython/core/debugger.py @@ -19,7 +19,7 @@ Global Configuration -------------------- The IPython debugger will by read the global ``~/.pdbrc`` file. -That is to say you can list all comands supported by ipdb in your `~/.pdbrc` +That is to say you can list all commands supported by ipdb in your `~/.pdbrc` configuration file, to globally configure pdb. Example:: @@ -177,7 +177,7 @@ def BdbQuit_excepthook(et, ev, tb, excepthook=None): parameter. """ raise ValueError( - "`BdbQuit_excepthook` is deprecated since version 5.1. It is still arround only because it is still imported by ipdb.", + "`BdbQuit_excepthook` is deprecated since version 5.1. It is still around only because it is still imported by ipdb.", ) diff --git a/contrib/python/ipython/py3/IPython/core/display.py b/contrib/python/ipython/py3/IPython/core/display.py index 5c4557b150..c3c44016f4 100644 --- a/contrib/python/ipython/py3/IPython/core/display.py +++ b/contrib/python/ipython/py3/IPython/core/display.py @@ -21,13 +21,35 @@ from IPython.testing.skipdoctest import skip_doctest from . import display_functions -__all__ = ['display_pretty', 'display_html', 'display_markdown', - 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', - 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', - 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', - 'GeoJSON', 'Javascript', 'Image', 'set_matplotlib_formats', - 'set_matplotlib_close', - 'Video'] +__all__ = [ + "display_pretty", + "display_html", + "display_markdown", + "display_svg", + "display_png", + "display_jpeg", + "display_webp", + "display_latex", + "display_json", + "display_javascript", + "display_pdf", + "DisplayObject", + "TextDisplayObject", + "Pretty", + "HTML", + "Markdown", + "Math", + "Latex", + "SVG", + "ProgressBar", + "JSON", + "GeoJSON", + "Javascript", + "Image", + "set_matplotlib_formats", + "set_matplotlib_close", + "Video", +] _deprecated_names = ["display", "clear_output", "publish_display_data", "update_display", "DisplayHandle"] @@ -200,6 +222,23 @@ def display_jpeg(*objs, **kwargs): _display_mimetype('image/jpeg', objs, **kwargs) +def display_webp(*objs, **kwargs): + """Display the WEBP representation of an object. + + Parameters + ---------- + *objs : object + The Python objects to display, or if raw=True raw JPEG data to + display. + raw : bool + Are the data objects raw data or Python objects that need to be + formatted before display? [default: False] + metadata : dict (optional) + Metadata to be associated with the specific mimetype output. + """ + _display_mimetype("image/webp", objs, **kwargs) + + def display_latex(*objs, **kwargs): """Display the LaTeX representation of an object. @@ -776,9 +815,14 @@ class Javascript(TextDisplayObject): r += _lib_t2*len(self.lib) return r -# constants for identifying png/jpeg data -_PNG = b'\x89PNG\r\n\x1a\n' -_JPEG = b'\xff\xd8' + +# constants for identifying png/jpeg/gif/webp data +_PNG = b"\x89PNG\r\n\x1a\n" +_JPEG = b"\xff\xd8" +_GIF1 = b"GIF87a" +_GIF2 = b"GIF89a" +_WEBP = b"WEBP" + def _pngxy(data): """read the (width, height) from a PNG header""" @@ -786,6 +830,7 @@ def _pngxy(data): # next 8 bytes are width/height return struct.unpack('>ii', data[ihdr+4:ihdr+12]) + def _jpegxy(data): """read the (width, height) from a JPEG header""" # adapted from http://www.64lines.com/jpeg-width-height @@ -805,22 +850,45 @@ def _jpegxy(data): h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) return w, h + def _gifxy(data): """read the (width, height) from a GIF header""" return struct.unpack('<HH', data[6:10]) +def _webpxy(data): + """read the (width, height) from a WEBP header""" + if data[12:16] == b"VP8 ": + width, height = struct.unpack("<HH", data[24:30]) + width = width & 0x3FFF + height = height & 0x3FFF + return (width, height) + elif data[12:16] == b"VP8L": + size_info = struct.unpack("<I", data[21:25])[0] + width = 1 + ((size_info & 0x3F) << 8) | (size_info >> 24) + height = 1 + ( + (((size_info >> 8) & 0xF) << 10) + | (((size_info >> 14) & 0x3FC) << 2) + | ((size_info >> 22) & 0x3) + ) + return (width, height) + else: + raise ValueError("Not a valid WEBP header") + + class Image(DisplayObject): - _read_flags = 'rb' - _FMT_JPEG = u'jpeg' - _FMT_PNG = u'png' - _FMT_GIF = u'gif' - _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF] + _read_flags = "rb" + _FMT_JPEG = "jpeg" + _FMT_PNG = "png" + _FMT_GIF = "gif" + _FMT_WEBP = "webp" + _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF, _FMT_WEBP] _MIMETYPES = { - _FMT_PNG: 'image/png', - _FMT_JPEG: 'image/jpeg', - _FMT_GIF: 'image/gif', + _FMT_PNG: "image/png", + _FMT_JPEG: "image/jpeg", + _FMT_GIF: "image/gif", + _FMT_WEBP: "image/webp", } def __init__( @@ -837,7 +905,7 @@ class Image(DisplayObject): metadata=None, alt=None, ): - """Create a PNG/JPEG/GIF image object given raw data. + """Create a PNG/JPEG/GIF/WEBP image object given raw data. When this object is returned by an input cell or passed to the display function, it will result in the image being displayed @@ -858,7 +926,7 @@ class Image(DisplayObject): Images from a file are always embedded. format : unicode - The format of the image data (png/jpeg/jpg/gif). If a filename or URL is given + The format of the image data (png/jpeg/jpg/gif/webp). If a filename or URL is given for format will be inferred from the filename extension. embed : bool @@ -942,6 +1010,8 @@ class Image(DisplayObject): format = self._FMT_PNG elif ext == u'gif': format = self._FMT_GIF + elif ext == "webp": + format = self._FMT_WEBP else: format = ext.lower() elif isinstance(data, bytes): @@ -949,6 +1019,12 @@ class Image(DisplayObject): # only if format has not been specified. if data[:2] == _JPEG: format = self._FMT_JPEG + elif data[:8] == _PNG: + format = self._FMT_PNG + elif data[8:12] == _WEBP: + format = self._FMT_WEBP + elif data[:6] == _GIF1 or data[:6] == _GIF2: + format = self._FMT_GIF # failed to detect format, default png if format is None: diff --git a/contrib/python/ipython/py3/IPython/core/guarded_eval.py b/contrib/python/ipython/py3/IPython/core/guarded_eval.py index d8ac9928af..39fe853f58 100644 --- a/contrib/python/ipython/py3/IPython/core/guarded_eval.py +++ b/contrib/python/ipython/py3/IPython/core/guarded_eval.py @@ -132,7 +132,7 @@ def _get_external(module_name: str, access_path: Sequence[str]): Raises: * `KeyError` if module is removed not found, and - * `AttributeError` if acess path does not match an exported object + * `AttributeError` if access path does not match an exported object """ member_type = sys.modules[module_name] for attr in access_path: @@ -235,7 +235,7 @@ class SelectivePolicy(EvaluationPolicy): accept = has_original_attr and has_original_attribute if accept: - # We still need to check for overriden properties. + # We still need to check for overridden properties. value_class = type(value) if not hasattr(value_class, attr): @@ -332,7 +332,7 @@ class EvaluationContext(NamedTuple): evaluation: Literal[ "forbidden", "minimal", "limited", "unsafe", "dangerous" ] = "forbidden" - #: Whether the evalution of code takes place inside of a subscript. + #: Whether the evaluation of code takes place inside of a subscript. #: Useful for evaluating ``:-1, 'col'`` in ``df[:-1, 'col']``. in_subscript: bool = False @@ -373,7 +373,7 @@ def guarded_eval(code: str, context: EvaluationContext): # getitem at all, for example it fails on simple `[0][1]` if context.in_subscript: - # syntatic sugar for ellipsis (:) is only available in susbcripts + # syntactic sugar for ellipsis (:) is only available in subscripts # so we need to trick the ast parser into thinking that we have # a subscript, but we need to be able to later recognise that we did # it so we can ignore the actual __getitem__ operation diff --git a/contrib/python/ipython/py3/IPython/core/inputsplitter.py b/contrib/python/ipython/py3/IPython/core/inputsplitter.py index af7a12e6e0..092f21408a 100644 --- a/contrib/python/ipython/py3/IPython/core/inputsplitter.py +++ b/contrib/python/ipython/py3/IPython/core/inputsplitter.py @@ -97,7 +97,7 @@ def num_ini_spaces(s): """ warnings.warn( "`num_ini_spaces` is Pending Deprecation since IPython 8.17." - "It is considered fro removal in in future version. " + "It is considered for removal in in future version. " "Please open an issue if you believe it should be kept.", stacklevel=2, category=PendingDeprecationWarning, diff --git a/contrib/python/ipython/py3/IPython/core/interactiveshell.py b/contrib/python/ipython/py3/IPython/core/interactiveshell.py index d05cb451f8..07fb807760 100644 --- a/contrib/python/ipython/py3/IPython/core/interactiveshell.py +++ b/contrib/python/ipython/py3/IPython/core/interactiveshell.py @@ -1627,7 +1627,7 @@ class InteractiveShell(SingletonConfigurable): Returns ------- parts_ok: bool - wether we were properly able to parse parts. + whether we were properly able to parse parts. parts: list of str extracted parts diff --git a/contrib/python/ipython/py3/IPython/core/magics/ast_mod.py b/contrib/python/ipython/py3/IPython/core/magics/ast_mod.py index fa54791443..dc3c5bc768 100644 --- a/contrib/python/ipython/py3/IPython/core/magics/ast_mod.py +++ b/contrib/python/ipython/py3/IPython/core/magics/ast_mod.py @@ -5,7 +5,7 @@ with ast-transformers it is not easy to directly manipulate ast. IPython has pre-code and post-code hooks, but are ran from within the IPython -machinery so may be inappropriate, for example for performance mesurement. +machinery so may be inappropriate, for example for performance measurement. This module give you tools to simplify this, and expose 2 classes: diff --git a/contrib/python/ipython/py3/IPython/core/magics/code.py b/contrib/python/ipython/py3/IPython/core/magics/code.py index 4f1574dcef..834ca51473 100644 --- a/contrib/python/ipython/py3/IPython/core/magics/code.py +++ b/contrib/python/ipython/py3/IPython/core/magics/code.py @@ -153,7 +153,9 @@ def strip_initial_indent(lines): for line in it: if line.startswith(indent): - yield line[len(indent):] + yield line[len(indent) :] + elif line in ("\n", "\r\n") or len(line) == 0: + yield line else: # Less indented than the first line - stop dedenting yield line diff --git a/contrib/python/ipython/py3/IPython/core/magics/execution.py b/contrib/python/ipython/py3/IPython/core/magics/execution.py index abfc4cbda7..3aa0a27fc2 100644 --- a/contrib/python/ipython/py3/IPython/core/magics/execution.py +++ b/contrib/python/ipython/py3/IPython/core/magics/execution.py @@ -195,12 +195,16 @@ class ExecutionMagics(Magics): """Run a statement through the python code profiler. - Usage, in line mode: + **Usage, in line mode:** + %prun [options] statement - Usage, in cell mode: + **Usage, in cell mode:** + %%prun [options] [statement] + code... + code... In cell mode, the additional code lines are appended to the (possibly @@ -1028,11 +1032,16 @@ class ExecutionMagics(Magics): def timeit(self, line='', cell=None, local_ns=None): """Time execution of a Python statement or expression - Usage, in line mode: + **Usage, in line mode:** + %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement - or in cell mode: + + **or in cell mode:** + %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code + code + code... Time execution of a Python statement or expression using the timeit @@ -1046,6 +1055,7 @@ class ExecutionMagics(Magics): body has access to any variables created in the setup code. Options: + -n<N>: execute the given statement <N> times in a loop. If <N> is not provided, <N> is determined so as to get sufficient accuracy. @@ -1066,7 +1076,7 @@ class ExecutionMagics(Magics): -q: Quiet, do not print result. -o: return a TimeitResult that can be stored in a variable to inspect - the result in more details. + the result in more details. .. versionchanged:: 7.3 User variables are no longer expanded, diff --git a/contrib/python/ipython/py3/IPython/core/magics/packaging.py b/contrib/python/ipython/py3/IPython/core/magics/packaging.py index 09d4117270..ed1c1274f3 100644 --- a/contrib/python/ipython/py3/IPython/core/magics/packaging.py +++ b/contrib/python/ipython/py3/IPython/core/magics/packaging.py @@ -162,3 +162,20 @@ class PackagingMagics(Magics): """ micromamba = _get_conda_like_executable("micromamba") self._run_command(micromamba, line) + + @line_magic + def uv(self, line): + """Run the uv package manager within the current kernel. + + Usage: + %uv pip install [pkgs] + """ + python = sys.executable + if sys.platform == "win32": + python = '"' + python + '"' + else: + python = shlex.quote(python) + + self.shell.system(" ".join([python, "-m", "uv", line])) + + print("Note: you may need to restart the kernel to use updated packages.") diff --git a/contrib/python/ipython/py3/IPython/core/oinspect.py b/contrib/python/ipython/py3/IPython/core/oinspect.py index 8aa8429e5d..a4fdc28bde 100644 --- a/contrib/python/ipython/py3/IPython/core/oinspect.py +++ b/contrib/python/ipython/py3/IPython/core/oinspect.py @@ -460,7 +460,7 @@ class Inspector(Colorable): mime_hooks = traitlets.Dict( config=True, - help="dictionary of mime to callable to add informations into help mimebundle dict", + help="dictionary of mime to callable to add information into help mimebundle dict", ).tag(config=True) def __init__( diff --git a/contrib/python/ipython/py3/IPython/core/page.py b/contrib/python/ipython/py3/IPython/core/page.py index 31b314ec46..2eb6c399b3 100644 --- a/contrib/python/ipython/py3/IPython/core/page.py +++ b/contrib/python/ipython/py3/IPython/core/page.py @@ -125,7 +125,7 @@ def _detect_screen_size(screen_lines_def): # print('***Screen size:',screen_lines_real,'lines x', # screen_cols,'columns.') # dbg -def pager_page(strng, start=0, screen_lines=0, pager_cmd=None): +def pager_page(strng, start=0, screen_lines=0, pager_cmd=None) -> None: """Display a string, piping through a pager after a certain length. strng can be a mime-bundle dict, supplying multiple representations, @@ -239,7 +239,7 @@ def pager_page(strng, start=0, screen_lines=0, pager_cmd=None): page_dumb(strng,screen_lines=screen_lines) -def page(data, start=0, screen_lines=0, pager_cmd=None): +def page(data, start: int = 0, screen_lines: int = 0, pager_cmd=None): """Display content in a pager, piping through a pager after a certain length. data can be a mime-bundle dict, supplying multiple representations, diff --git a/contrib/python/ipython/py3/IPython/core/prefilter.py b/contrib/python/ipython/py3/IPython/core/prefilter.py index a29df0c27a..fc7b1c3416 100644 --- a/contrib/python/ipython/py3/IPython/core/prefilter.py +++ b/contrib/python/ipython/py3/IPython/core/prefilter.py @@ -512,8 +512,10 @@ class AutocallChecker(PrefilterChecker): callable(oinfo.obj) and (not self.exclude_regexp.match(line_info.the_rest)) and self.function_name_regexp.match(line_info.ifun) - and line_info.raw_the_rest.startswith(" ") - or not line_info.raw_the_rest.strip() + and ( + line_info.raw_the_rest.startswith(" ") + or not line_info.raw_the_rest.strip() + ) ): return self.prefilter_manager.get_handler_by_name("auto") else: diff --git a/contrib/python/ipython/py3/IPython/core/pylabtools.py b/contrib/python/ipython/py3/IPython/core/pylabtools.py index 5c926a9c10..ad2fc74e9e 100644 --- a/contrib/python/ipython/py3/IPython/core/pylabtools.py +++ b/contrib/python/ipython/py3/IPython/core/pylabtools.py @@ -528,7 +528,7 @@ def _list_matplotlib_backends_and_gui_loops() -> list[str]: # Matplotlib and IPython do not always use the same gui framework name. -# Always use the approprate one of these conversion functions when passing a +# Always use the appropriate one of these conversion functions when passing a # gui framework name to/from Matplotlib. def _convert_gui_to_matplotlib(gui: str | None) -> str | None: if gui and gui.lower() == "osx": diff --git a/contrib/python/ipython/py3/IPython/core/release.py b/contrib/python/ipython/py3/IPython/core/release.py index fb5a54da6a..d9eb28aa95 100644 --- a/contrib/python/ipython/py3/IPython/core/release.py +++ b/contrib/python/ipython/py3/IPython/core/release.py @@ -16,7 +16,7 @@ # release. 'dev' as a _version_extra string means this is a development # version _version_major = 8 -_version_minor = 28 +_version_minor = 29 _version_patch = 0 _version_extra = ".dev" # _version_extra = "rc1" @@ -32,22 +32,13 @@ if _version_extra: version = __version__ # backwards compatibility name version_info = (_version_major, _version_minor, _version_patch, _version_extra) -# Change this when incrementing the kernel protocol version -kernel_protocol_version_info = (5, 0) -kernel_protocol_version = "%i.%i" % kernel_protocol_version_info license = "BSD-3-Clause" -authors = {'Fernando' : ('Fernando Perez','fperez.net@gmail.com'), - 'Janko' : ('Janko Hauser','jhauser@zscout.de'), - 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), - 'Ville' : ('Ville Vainio','vivainio@gmail.com'), - 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'), - 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com'), - 'Thomas' : ('Thomas A. Kluyver', 'takowl@gmail.com'), - 'Jorgen' : ('Jorgen Stenarson', 'jorgen.stenarson@bostream.nu'), - 'Matthias' : ('Matthias Bussonnier', 'bussonniermatthias@gmail.com'), - } +authors = { + "Fernando": ("Fernando Perez", "fperez.net@gmail.com"), + "M": ("M Bussonnier", "mbussonnier@gmail.com"), +} author = 'The IPython Development Team' diff --git a/contrib/python/ipython/py3/IPython/lib/pretty.py b/contrib/python/ipython/py3/IPython/lib/pretty.py index 8a24632d60..a232e4edf6 100644 --- a/contrib/python/ipython/py3/IPython/lib/pretty.py +++ b/contrib/python/ipython/py3/IPython/lib/pretty.py @@ -541,7 +541,7 @@ class RawText: 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 + # dunders are to avoid clashes with kwargs, as python's name managing # will kick in. self = __self self.name = __name @@ -555,7 +555,7 @@ class CallExpression: return inner def _repr_pretty_(self, p, cycle): - # dunders are to avoid clashes with kwargs, as python's name manging + # dunders are to avoid clashes with kwargs, as python's name managing # will kick in. started = False @@ -724,8 +724,15 @@ class _ReFlags: def _repr_pretty_(self, p, cycle): done_one = False - for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', - 'UNICODE', 'VERBOSE', 'DEBUG'): + for flag in ( + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "UNICODE", + "VERBOSE", + "DEBUG", + ): if self.value & getattr(re, flag): if done_one: p.text('|') diff --git a/contrib/python/ipython/py3/IPython/terminal/shortcuts/auto_suggest.py b/contrib/python/ipython/py3/IPython/terminal/shortcuts/auto_suggest.py index 65f91577ce..94a94a88c1 100644 --- a/contrib/python/ipython/py3/IPython/terminal/shortcuts/auto_suggest.py +++ b/contrib/python/ipython/py3/IPython/terminal/shortcuts/auto_suggest.py @@ -77,7 +77,7 @@ class NavigableAutoSuggestFromHistory(AutoSuggestFromHistory): def connect(self, pt_app: PromptSession): self._connected_apps.append(pt_app) # note: `on_text_changed` could be used for a bit different behaviour - # on character deletion (i.e. reseting history position on backspace) + # on character deletion (i.e. resetting history position on backspace) pt_app.default_buffer.on_text_insert.add_handler(self.reset_history_position) pt_app.default_buffer.on_cursor_position_changed.add_handler(self._dismiss) diff --git a/contrib/python/ipython/py3/IPython/terminal/shortcuts/filters.py b/contrib/python/ipython/py3/IPython/terminal/shortcuts/filters.py index 7c9d6a9c41..8e7c8d037c 100644 --- a/contrib/python/ipython/py3/IPython/terminal/shortcuts/filters.py +++ b/contrib/python/ipython/py3/IPython/terminal/shortcuts/filters.py @@ -207,7 +207,7 @@ class PassThrough(Filter): pass_through = PassThrough() # these one is callable and re-used multiple times hence needs to be -# only defined once beforhand so that transforming back to human-readable +# only defined once beforehand so that transforming back to human-readable # names works well in the documentation. default_buffer_focused = has_focus(DEFAULT_BUFFER) diff --git a/contrib/python/ipython/py3/IPython/testing/tools.py b/contrib/python/ipython/py3/IPython/testing/tools.py index b030349048..aa54443ad0 100644 --- a/contrib/python/ipython/py3/IPython/testing/tools.py +++ b/contrib/python/ipython/py3/IPython/testing/tools.py @@ -36,7 +36,7 @@ from . import skipdoctest doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco @doctest_deco -def full_path(startPath,files): +def full_path(startPath: str, files: list[str]) -> list[str]: """Make full paths for all the listed files, based on startPath. Only the base part of startPath is kept, since this routine is typically @@ -49,7 +49,7 @@ def full_path(startPath,files): Initial path to use as the base for the results. This path is split using os.path.split() and only its first component is kept. - files : string or list + files : list One or more files. Examples @@ -61,13 +61,8 @@ def full_path(startPath,files): >>> full_path('/foo',['a.txt','b.txt']) ['/a.txt', '/b.txt'] - If a single file is given, the output is still a list:: - - >>> full_path('/foo','a.txt') - ['/a.txt'] """ - - files = list_strings(files) + assert isinstance(files, list) base = os.path.split(startPath)[0] return [ os.path.join(base,f) for f in files ] diff --git a/contrib/python/ipython/py3/IPython/utils/_sysinfo.py b/contrib/python/ipython/py3/IPython/utils/_sysinfo.py index 304813b0f5..261309bb28 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 = "a9c7369d7" +commit = "af19fb054" diff --git a/contrib/python/ipython/py3/IPython/utils/frame.py b/contrib/python/ipython/py3/IPython/utils/frame.py index 808906bda8..3d0c1b7189 100644 --- a/contrib/python/ipython/py3/IPython/utils/frame.py +++ b/contrib/python/ipython/py3/IPython/utils/frame.py @@ -15,6 +15,7 @@ Utilities for working with stack frames. #----------------------------------------------------------------------------- import sys +from typing import Any #----------------------------------------------------------------------------- # Code @@ -51,7 +52,7 @@ def extract_vars(*names,**kw): return dict((k,callerNS[k]) for k in names) -def extract_vars_above(*names): +def extract_vars_above(*names: list[str]): """Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names @@ -65,7 +66,7 @@ def extract_vars_above(*names): return dict((k,callerNS[k]) for k in names) -def debugx(expr,pre_msg=''): +def debugx(expr: str, pre_msg: str = ""): """Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both @@ -84,7 +85,8 @@ def debugx(expr,pre_msg=''): # deactivate it by uncommenting the following line, which makes it a no-op #def debugx(expr,pre_msg=''): pass -def extract_module_locals(depth=0): + +def extract_module_locals(depth: int = 0) -> tuple[Any, Any]: """Returns (module, locals) of the function `depth` frames away from the caller""" f = sys._getframe(depth + 1) global_ns = f.f_globals diff --git a/contrib/python/ipython/py3/IPython/utils/text.py b/contrib/python/ipython/py3/IPython/utils/text.py index 46b3bb0e46..8f1d380fc5 100644 --- a/contrib/python/ipython/py3/IPython/utils/text.py +++ b/contrib/python/ipython/py3/IPython/utils/text.py @@ -16,7 +16,20 @@ import warnings from string import Formatter from pathlib import Path -from typing import List, Dict, Tuple, Optional, cast, Sequence, Mapping, Any +from typing import ( + List, + Dict, + Tuple, + Optional, + cast, + Sequence, + Mapping, + Any, + Union, + Callable, + Iterator, + TypeVar, +) if sys.version_info < (3, 12): from typing_extensions import Self @@ -138,8 +151,13 @@ class SList(list): p = paths = property(get_paths) - def grep(self, pattern, prune = False, field = None): - """ Return all strings matching 'pattern' (a regex or callable) + def grep( + self, + pattern: Union[str, Callable[[Any], re.Match[str] | None]], + prune: bool = False, + field: Optional[int] = None, + ) -> Self: + """Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. @@ -154,7 +172,7 @@ class SList(list): a.grep('chm', field=-1) """ - def match_target(s): + def match_target(s: str) -> str: if field is None: return s parts = s.split() @@ -169,12 +187,12 @@ class SList(list): else: pred = pattern if not prune: - return SList([el for el in self if pred(match_target(el))]) + return type(self)([el for el in self if pred(match_target(el))]) else: - return SList([el for el in self if not pred(match_target(el))]) + return type(self)([el for el in self if not pred(match_target(el))]) - def fields(self, *fields): - """ Collect whitespace-separated fields from string list + def fields(self, *fields: List[str]) -> List[List[str]]: + """Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. @@ -209,8 +227,12 @@ class SList(list): return res - def sort(self,field= None, nums = False): - """ sort by specified fields (see fields()) + def sort( # type:ignore[override] + self, + field: Optional[List[str]] = None, + nums: bool = False, + ) -> Self: + """sort by specified fields (see fields()) Example:: @@ -236,7 +258,7 @@ class SList(list): dsu.sort() - return SList([t[1] for t in dsu]) + return type(self)([t[1] for t in dsu]) # FIXME: We need to reimplement type specific displayhook and then add this @@ -255,7 +277,7 @@ class SList(list): # print_slist = result_display.register(SList)(print_slist) -def indent(instr,nspaces=4, ntabs=0, flatten=False): +def indent(instr: str, nspaces: int = 4, ntabs: int = 0, flatten: bool = False) -> str: """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. @@ -275,7 +297,7 @@ def indent(instr,nspaces=4, ntabs=0, flatten=False): Returns ------- - str|unicode : string indented by ntabs and nspaces. + str : string indented by ntabs and nspaces. """ if instr is None: @@ -292,7 +314,7 @@ def indent(instr,nspaces=4, ntabs=0, flatten=False): return outstr -def list_strings(arg): +def list_strings(arg: Union[str, List[str]]) -> List[str]: """Always return a list of strings, given a string or list of strings as input. @@ -316,7 +338,7 @@ def list_strings(arg): return arg -def marquee(txt='',width=78,mark='*'): +def marquee(txt: str = "", width: int = 78, mark: str = "*") -> str: """Return the input string centered in a 'marquee'. Examples @@ -343,11 +365,12 @@ def marquee(txt='',width=78,mark='*'): ini_spaces_re = re.compile(r'^(\s+)') -def num_ini_spaces(strng): + +def num_ini_spaces(strng: str) -> int: """Return the number of initial spaces in a string""" warnings.warn( "`num_ini_spaces` is Pending Deprecation since IPython 8.17." - "It is considered fro removal in in future version. " + "It is considered for removal in in future version. " "Please open an issue if you believe it should be kept.", stacklevel=2, category=PendingDeprecationWarning, @@ -359,7 +382,7 @@ def num_ini_spaces(strng): return 0 -def format_screen(strng): +def format_screen(strng: str) -> str: """Format a string for screen printing. This removes some latex-type format codes.""" @@ -396,7 +419,7 @@ def dedent(text: str) -> str: return '\n'.join([first, rest]) -def wrap_paragraphs(text, ncols=80): +def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]: """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple @@ -408,7 +431,7 @@ def wrap_paragraphs(text, ncols=80): """ warnings.warn( "`wrap_paragraphs` is Pending Deprecation since IPython 8.17." - "It is considered fro removal in in future version. " + "It is considered for removal in in future version. " "Please open an issue if you believe it should be kept.", stacklevel=2, category=PendingDeprecationWarning, @@ -428,7 +451,7 @@ def wrap_paragraphs(text, ncols=80): return out_ps -def strip_email_quotes(text): +def strip_email_quotes(text: str) -> str: """Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that @@ -478,7 +501,7 @@ def strip_email_quotes(text): return text -def strip_ansi(source): +def strip_ansi(source: str) -> str: """ Remove ansi escape codes from text. @@ -489,7 +512,7 @@ def strip_ansi(source): """ warnings.warn( "`strip_ansi` is Pending Deprecation since IPython 8.17." - "It is considered fro removal in in future version. " + "It is considered for removal in in future version. " "Please open an issue if you believe it should be kept.", stacklevel=2, category=PendingDeprecationWarning, @@ -519,7 +542,8 @@ class EvalFormatter(Formatter): In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") Out[3]: 'll' """ - def get_field(self, name, args, kwargs): + + def get_field(self, name: str, args: Any, kwargs: Any) -> Tuple[Any, str]: v = eval(name, kwargs) return v, name @@ -606,11 +630,15 @@ class DollarFormatter(FullEvalFormatter): In [4]: f.format('$a or {b}', a=1, b=2) Out[4]: '1 or 2' """ - _dollar_pattern_ignore_single_quote = re.compile(r"(.*?)\$(\$?[\w\.]+)(?=([^']*'[^']*')*[^']*$)") - def parse(self, fmt_string): - for literal_txt, field_name, format_spec, conversion \ - in Formatter.parse(self, fmt_string): - + + _dollar_pattern_ignore_single_quote = re.compile( + r"(.*?)\$(\$?[\w\.]+)(?=([^']*'[^']*')*[^']*$)" + ) + + def parse(self, fmt_string: str) -> Iterator[Tuple[Any, Any, Any, Any]]: # type: ignore + for literal_txt, field_name, format_spec, conversion in Formatter.parse( + self, fmt_string + ): # Find $foo patterns in the literal text. continue_from = 0 txt = "" @@ -627,14 +655,17 @@ class DollarFormatter(FullEvalFormatter): # Re-yield the {foo} style pattern yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) - def __repr__(self): + def __repr__(self) -> str: return "<DollarFormatter>" #----------------------------------------------------------------------------- # Utils to columnize a list of string #----------------------------------------------------------------------------- -def _col_chunks(l, max_rows, row_first=False): + +def _col_chunks( + l: List[int], max_rows: int, row_first: bool = False +) -> Iterator[List[int]]: """Yield successive max_rows-sized column chunks from l.""" if row_first: ncols = (len(l) // max_rows) + (len(l) % max_rows > 0) @@ -646,7 +677,7 @@ def _col_chunks(l, max_rows, row_first=False): def _find_optimal( - rlist: List[str], row_first: bool, separator_size: int, displaywidth: int + rlist: List[int], row_first: bool, separator_size: int, displaywidth: int ) -> Dict[str, Any]: """Calculate optimal info to columnize a list of string""" for max_rows in range(1, len(rlist) + 1): @@ -662,7 +693,10 @@ def _find_optimal( } -def _get_or_default(mylist, i, default=None): +T = TypeVar("T") + + +def _get_or_default(mylist: List[T], i: int, default: T) -> T: """return list item number, or default if don't exist""" if i >= len(mylist): return default @@ -727,7 +761,7 @@ def compute_item_matrix( """ warnings.warn( "`compute_item_matrix` is Pending Deprecation since IPython 8.17." - "It is considered fro removal in in future version. " + "It is considered for removal in in future version. " "Please open an issue if you believe it should be kept.", stacklevel=2, category=PendingDeprecationWarning, @@ -740,9 +774,31 @@ def compute_item_matrix( ) nrow, ncol = info["max_rows"], info["num_columns"] if row_first: - return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info) + return ( + [ + [ + _get_or_default( + items, r * ncol + c, default=empty + ) # type:ignore[misc] + for c in range(ncol) + ] + for r in range(nrow) + ], + info, + ) else: - return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info) + return ( + [ + [ + _get_or_default( + items, c * nrow + r, default=empty + ) # type:ignore[misc] + for c in range(ncol) + ] + for r in range(nrow) + ], + info, + ) def columnize( @@ -795,7 +851,9 @@ def columnize( return "\n".join(map(sjoin, fmatrix)) + "\n" -def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""): +def get_text_list( + list_: List[str], last_sep: str = " and ", sep: str = ", ", wrap_item_with: str = "" +) -> str: """ Return a string with a natural enumeration of items diff --git a/contrib/python/ipython/py3/ya.make b/contrib/python/ipython/py3/ya.make index b13b8d1baa..71ae1e14b1 100644 --- a/contrib/python/ipython/py3/ya.make +++ b/contrib/python/ipython/py3/ya.make @@ -2,7 +2,7 @@ PY3_LIBRARY() -VERSION(8.28.0) +VERSION(8.29.0) LICENSE(BSD-3-Clause) |