id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
176,671
from dataclasses import dataclass from inspect import signature from textwrap import dedent import ast import html import inspect import io as stdlib_io import linecache import os import sys import types import warnings from typing import Any, Optional, Dict, Union, List, Tuple from IPython.core import page from IPython.lib.pretty import pretty from IPython.testing.skipdoctest import skip_doctest from IPython.utils import PyColorize from IPython.utils import openpy from IPython.utils.dir2 import safe_hasattr from IPython.utils.path import compress_user from IPython.utils.text import indent from IPython.utils.wildcard import list_namespace from IPython.utils.wildcard import typestr2type from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable from IPython.utils.py3compat import cast_unicode from IPython.utils.colorable import Colorable from IPython.utils.decorators import undoc from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter def is_simple_callable(obj): """True if obj is a function ()""" return (inspect.isfunction(obj) or inspect.ismethod(obj) or \ isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type)) def safe_hasattr(obj, attr): """In recent versions of Python, hasattr() only catches AttributeError. This catches all errors. """ try: getattr(obj, attr) return True except: return False The provided code snippet includes necessary dependencies for implementing the `getargspec` function. Write a Python function `def getargspec(obj)` to solve the following problem: Wrapper around :func:`inspect.getfullargspec` In addition to functions and methods, this can also handle objects with a ``__call__`` attribute. DEPRECATED: Deprecated since 7.10. Do not use, will be removed. Here is the function: def getargspec(obj): """Wrapper around :func:`inspect.getfullargspec` In addition to functions and methods, this can also handle objects with a ``__call__`` attribute. DEPRECATED: Deprecated since 7.10. Do not use, will be removed. """ warnings.warn('`getargspec` function is deprecated as of IPython 7.10' 'and will be removed in future versions.', DeprecationWarning, stacklevel=2) if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): obj = obj.__call__ return inspect.getfullargspec(obj)
Wrapper around :func:`inspect.getfullargspec` In addition to functions and methods, this can also handle objects with a ``__call__`` attribute. DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
176,672
from dataclasses import dataclass from inspect import signature from textwrap import dedent import ast import html import inspect import io as stdlib_io import linecache import os import sys import types import warnings from typing import Any, Optional, Dict, Union, List, Tuple from IPython.core import page from IPython.lib.pretty import pretty from IPython.testing.skipdoctest import skip_doctest from IPython.utils import PyColorize from IPython.utils import openpy from IPython.utils.dir2 import safe_hasattr from IPython.utils.path import compress_user from IPython.utils.text import indent from IPython.utils.wildcard import list_namespace from IPython.utils.wildcard import typestr2type from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable from IPython.utils.py3compat import cast_unicode from IPython.utils.colorable import Colorable from IPython.utils.decorators import undoc from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter def format_argspec(argspec): """Format argspect, convenience wrapper around inspect's. This takes a dict instead of ordered arguments and calls inspect.format_argspec with the arguments in the necessary order. DEPRECATED (since 7.10): Do not use; will be removed in future versions. """ warnings.warn('`format_argspec` function is deprecated as of IPython 7.10' 'and will be removed in future versions.', DeprecationWarning, stacklevel=2) return inspect.formatargspec(argspec['args'], argspec['varargs'], argspec['varkw'], argspec['defaults']) The provided code snippet includes necessary dependencies for implementing the `call_tip` function. Write a Python function `def call_tip(oinfo, format_call=True)` to solve the following problem: DEPRECATED since 6.0. Extract call tip data from an oinfo dict. Here is the function: def call_tip(oinfo, format_call=True): """DEPRECATED since 6.0. Extract call tip data from an oinfo dict.""" warnings.warn( "`call_tip` function is deprecated as of IPython 6.0" "and will be removed in future versions.", DeprecationWarning, stacklevel=2, ) # Get call definition argspec = oinfo.get('argspec') if argspec is None: call_line = None else: # Callable objects will have 'self' as their first argument, prune # it out if it's there for clarity (since users do *not* pass an # extra first argument explicitly). try: has_self = argspec['args'][0] == 'self' except (KeyError, IndexError): pass else: if has_self: argspec['args'] = argspec['args'][1:] call_line = oinfo['name']+format_argspec(argspec) # Now get docstring. # The priority is: call docstring, constructor docstring, main one. doc = oinfo.get('call_docstring') if doc is None: doc = oinfo.get('init_docstring') if doc is None: doc = oinfo.get('docstring','') return call_line, doc
DEPRECATED since 6.0. Extract call tip data from an oinfo dict.
176,673
from dataclasses import dataclass from inspect import signature from textwrap import dedent import ast import html import inspect import io as stdlib_io import linecache import os import sys import types import warnings from typing import Any, Optional, Dict, Union, List, Tuple from IPython.core import page from IPython.lib.pretty import pretty from IPython.testing.skipdoctest import skip_doctest from IPython.utils import PyColorize from IPython.utils import openpy from IPython.utils.dir2 import safe_hasattr from IPython.utils.path import compress_user from IPython.utils.text import indent from IPython.utils.wildcard import list_namespace from IPython.utils.wildcard import typestr2type from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable from IPython.utils.py3compat import cast_unicode from IPython.utils.colorable import Colorable from IPython.utils.decorators import undoc from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter def _get_wrapped(obj): """Get the original object if wrapped in one or more @decorators Some objects automatically construct similar objects on any unrecognised attribute access (e.g. unittest.mock.call). To protect against infinite loops, this will arbitrarily cut off after 100 levels of obj.__wrapped__ attribute access. --TK, Jan 2016 """ orig_obj = obj i = 0 while safe_hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ i += 1 if i > 100: # __wrapped__ is probably a lie, so return the thing we started with return orig_obj return obj The provided code snippet includes necessary dependencies for implementing the `find_source_lines` function. Write a Python function `def find_source_lines(obj)` to solve the following problem: Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts. Here is the function: def find_source_lines(obj): """Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts. """ obj = _get_wrapped(obj) try: lineno = inspect.getsourcelines(obj)[1] except TypeError: # For instances, try the class object like getsource() does try: lineno = inspect.getsourcelines(obj.__class__)[1] except (OSError, TypeError): return None except OSError: return None return lineno
Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts.
176,674
from dataclasses import dataclass from inspect import signature from textwrap import dedent import ast import html import inspect import io as stdlib_io import linecache import os import sys import types import warnings from typing import Any, Optional, Dict, Union, List, Tuple from IPython.core import page from IPython.lib.pretty import pretty from IPython.testing.skipdoctest import skip_doctest from IPython.utils import PyColorize from IPython.utils import openpy from IPython.utils.dir2 import safe_hasattr from IPython.utils.path import compress_user from IPython.utils.text import indent from IPython.utils.wildcard import list_namespace from IPython.utils.wildcard import typestr2type from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable from IPython.utils.py3compat import cast_unicode from IPython.utils.colorable import Colorable from IPython.utils.decorators import undoc from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter The provided code snippet includes necessary dependencies for implementing the `_render_signature` function. Write a Python function `def _render_signature(obj_signature, obj_name) -> str` to solve the following problem: This was mostly taken from inspect.Signature.__str__. Look there for the comments. The only change is to add linebreaks when this gets too long. Here is the function: def _render_signature(obj_signature, obj_name) -> str: """ This was mostly taken from inspect.Signature.__str__. Look there for the comments. The only change is to add linebreaks when this gets too long. """ result = [] pos_only = False kw_only = True for param in obj_signature.parameters.values(): if param.kind == inspect.Parameter.POSITIONAL_ONLY: pos_only = True elif pos_only: result.append('/') pos_only = False if param.kind == inspect.Parameter.VAR_POSITIONAL: kw_only = False elif param.kind == inspect.Parameter.KEYWORD_ONLY and kw_only: result.append('*') kw_only = False result.append(str(param)) if pos_only: result.append('/') # add up name, parameters, braces (2), and commas if len(obj_name) + sum(len(r) + 2 for r in result) > 75: # This doesn’t fit behind “Signature: ” in an inspect window. rendered = '{}(\n{})'.format(obj_name, ''.join( ' {},\n'.format(r) for r in result) ) else: rendered = '{}({})'.format(obj_name, ', '.join(result)) if obj_signature.return_annotation is not inspect._empty: anno = inspect.formatannotation(obj_signature.return_annotation) rendered += ' -> {}'.format(anno) return rendered
This was mostly taken from inspect.Signature.__str__. Look there for the comments. The only change is to add linebreaks when this gets too long.
176,675
from io import BytesIO from binascii import b2a_base64 from functools import partial import warnings from IPython.core.display import _pngxy from IPython.utils.decorators import flag_calls The provided code snippet includes necessary dependencies for implementing the `mpl_runner` function. Write a Python function `def mpl_runner(safe_execfile)` to solve the following problem: Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. Here is the function: def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. """ def mpl_execfile(fname,*where,**kw): """matplotlib-aware wrapper around safe_execfile. Its interface is identical to that of the :func:`execfile` builtin. This is ultimately a call to execfile(), but wrapped in safeties to properly handle interactive rendering.""" import matplotlib import matplotlib.pyplot as plt #print '*** Matplotlib runner ***' # dbg # turn off rendering until end of script is_interactive = matplotlib.rcParams['interactive'] matplotlib.interactive(False) safe_execfile(fname,*where,**kw) matplotlib.interactive(is_interactive) # make rendering call now, if the user tried to do it if plt.draw_if_interactive.called: plt.draw() plt.draw_if_interactive.called = False # re-draw everything that is stale try: da = plt.draw_all except AttributeError: pass else: da() return mpl_execfile
Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function.
176,676
from io import BytesIO from binascii import b2a_base64 from functools import partial import warnings from IPython.core.display import _pngxy from IPython.utils.decorators import flag_calls backends = { "tk": "TkAgg", "gtk": "GTKAgg", "gtk3": "GTK3Agg", "gtk4": "GTK4Agg", "wx": "WXAgg", "qt4": "Qt4Agg", "qt5": "Qt5Agg", "qt6": "QtAgg", "qt": "Qt5Agg", "osx": "MacOSX", "nbagg": "nbAgg", "webagg": "WebAgg", "notebook": "nbAgg", "agg": "agg", "svg": "svg", "pdf": "pdf", "ps": "ps", "inline": "module://matplotlib_inline.backend_inline", "ipympl": "module://ipympl.backend_nbagg", "widget": "module://ipympl.backend_nbagg", } backend2gui = dict(zip(backends.values(), backends.keys())) backend2gui["GTK"] = backend2gui["GTKCairo"] = "gtk" backend2gui["GTK3Cairo"] = "gtk3" backend2gui["GTK4Cairo"] = "gtk4" backend2gui["WX"] = "wx" backend2gui["CocoaAgg"] = "osx" backend2gui["QtAgg"] = "qt" backend2gui["Qt4Agg"] = "qt" backend2gui["Qt5Agg"] = "qt" del backend2gui["nbAgg"] del backend2gui["agg"] del backend2gui["svg"] del backend2gui["pdf"] del backend2gui["ps"] del backend2gui["module://matplotlib_inline.backend_inline"] del backend2gui["module://ipympl.backend_nbagg"] The provided code snippet includes necessary dependencies for implementing the `find_gui_and_backend` function. Write a Python function `def find_gui_and_backend(gui=None, gui_select=None)` to solve the following problem: Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline','agg'). gui_select : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). This is any gui already selected by the shell. Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg'). Here is the function: def find_gui_and_backend(gui=None, gui_select=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline','agg'). gui_select : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). This is any gui already selected by the shell. Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg'). """ import matplotlib if gui and gui != 'auto': # select backend based on requested gui backend = backends[gui] if gui == 'agg': gui = None else: # We need to read the backend from the original data structure, *not* # from mpl.rcParams, since a prior invocation of %matplotlib may have # overwritten that. # WARNING: this assumes matplotlib 1.1 or newer!! backend = matplotlib.rcParamsOrig['backend'] # In this case, we need to find what the appropriate gui selection call # should be for IPython, so we can activate inputhook accordingly gui = backend2gui.get(backend, None) # If we have already had a gui active, we need it and inline are the # ones allowed. if gui_select and gui != gui_select: gui = gui_select backend = backends[gui] return gui, backend
Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline','agg'). gui_select : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). This is any gui already selected by the shell. Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg').
176,677
from io import BytesIO from binascii import b2a_base64 from functools import partial import warnings from IPython.core.display import _pngxy from IPython.utils.decorators import flag_calls def getfigs(*fig_nums): """Get a list of matplotlib figures by figure numbers. If no arguments are given, all available figures are returned. If the argument list contains references to invalid figures, a warning is printed but the function continues pasting further figures. Parameters ---------- figs : tuple A tuple of ints giving the figure numbers of the figures to return. """ from matplotlib._pylab_helpers import Gcf if not fig_nums: fig_managers = Gcf.get_all_fig_managers() return [fm.canvas.figure for fm in fig_managers] else: figs = [] for num in fig_nums: f = Gcf.figs.get(num) if f is None: print('Warning: figure %s not available.' % num) else: figs.append(f.canvas.figure) return figs def figsize(sizex, sizey): """Set the default figure size to be [sizex, sizey]. This is just an easy to remember, convenience wrapper that sets:: matplotlib.rcParams['figure.figsize'] = [sizex, sizey] """ import matplotlib matplotlib.rcParams['figure.figsize'] = [sizex, sizey] The provided code snippet includes necessary dependencies for implementing the `import_pylab` function. Write a Python function `def import_pylab(user_ns, import_all=True)` to solve the following problem: Populate the namespace with pylab-related values. Imports matplotlib, pylab, numpy, and everything from pylab and numpy. Also imports a few names from IPython (figsize, display, getfigs) Here is the function: def import_pylab(user_ns, import_all=True): """Populate the namespace with pylab-related values. Imports matplotlib, pylab, numpy, and everything from pylab and numpy. Also imports a few names from IPython (figsize, display, getfigs) """ # Import numpy as np/pyplot as plt are conventions we're trying to # somewhat standardize on. Making them available to users by default # will greatly help this. s = ("import numpy\n" "import matplotlib\n" "from matplotlib import pylab, mlab, pyplot\n" "np = numpy\n" "plt = pyplot\n" ) exec(s, user_ns) if import_all: s = ("from matplotlib.pylab import *\n" "from numpy import *\n") exec(s, user_ns) # IPython symbols to add user_ns['figsize'] = figsize from IPython.display import display # Add display and getfigs to the user's namespace user_ns['display'] = display user_ns['getfigs'] = getfigs
Populate the namespace with pylab-related values. Imports matplotlib, pylab, numpy, and everything from pylab and numpy. Also imports a few names from IPython (figsize, display, getfigs)
176,678
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings The provided code snippet includes necessary dependencies for implementing the `leading_empty_lines` function. Write a Python function `def leading_empty_lines(lines)` to solve the following problem: Remove leading empty lines If the leading lines are empty or contain only whitespace, they will be removed. Here is the function: def leading_empty_lines(lines): """Remove leading empty lines If the leading lines are empty or contain only whitespace, they will be removed. """ if not lines: return lines for i, line in enumerate(lines): if line and not line.isspace(): return lines[i:] return lines
Remove leading empty lines If the leading lines are empty or contain only whitespace, they will be removed.
176,679
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings _indent_re = re.compile(r'^[ \t]+') The provided code snippet includes necessary dependencies for implementing the `leading_indent` function. Write a Python function `def leading_indent(lines)` to solve the following problem: Remove leading indentation. If the first line starts with a spaces or tabs, the same whitespace will be removed from each following line in the cell. Here is the function: def leading_indent(lines): """Remove leading indentation. If the first line starts with a spaces or tabs, the same whitespace will be removed from each following line in the cell. """ if not lines: return lines m = _indent_re.match(lines[0]) if not m: return lines space = m.group(0) n = len(space) return [l[n:] if l.startswith(space) else l for l in lines]
Remove leading indentation. If the first line starts with a spaces or tabs, the same whitespace will be removed from each following line in the cell.
176,680
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings def cell_magic(lines): if not lines or not lines[0].startswith('%%'): return lines if re.match(r'%%\w+\?', lines[0]): # This case will be handled by help_end return lines magic_name, _, first_line = lines[0][2:].rstrip().partition(' ') body = ''.join(lines[1:]) return ['get_ipython().run_cell_magic(%r, %r, %r)\n' % (magic_name, first_line, body)]
null
176,681
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings Optional: _SpecialForm = ... The provided code snippet includes necessary dependencies for implementing the `_find_assign_op` function. Write a Python function `def _find_assign_op(token_line) -> Optional[int]` to solve the following problem: Get the index of the first assignment in the line ('=' not inside brackets) Note: We don't try to support multiple special assignment (a = b = %foo) Here is the function: def _find_assign_op(token_line) -> Optional[int]: """Get the index of the first assignment in the line ('=' not inside brackets) Note: We don't try to support multiple special assignment (a = b = %foo) """ paren_level = 0 for i, ti in enumerate(token_line): s = ti.string if s == '=' and paren_level == 0: return i if s in {'(','[','{'}: paren_level += 1 elif s in {')', ']', '}'}: if paren_level > 0: paren_level -= 1 return None
Get the index of the first assignment in the line ('=' not inside brackets) Note: We don't try to support multiple special assignment (a = b = %foo)
176,682
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings The provided code snippet includes necessary dependencies for implementing the `find_end_of_continued_line` function. Write a Python function `def find_end_of_continued_line(lines, start_line: int)` to solve the following problem: Find the last line of a line explicitly extended using backslashes. Uses 0-indexed line numbers. Here is the function: def find_end_of_continued_line(lines, start_line: int): """Find the last line of a line explicitly extended using backslashes. Uses 0-indexed line numbers. """ end_line = start_line while lines[end_line].endswith('\\\n'): end_line += 1 if end_line >= len(lines): break return end_line
Find the last line of a line explicitly extended using backslashes. Uses 0-indexed line numbers.
176,683
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `assemble_continued_line` function. Write a Python function `def assemble_continued_line(lines, start: Tuple[int, int], end_line: int)` to solve the following problem: r"""Assemble a single line from multiple continued line pieces Continued lines are lines ending in ``\``, and the line following the last ``\`` in the block. For example, this code continues over multiple lines:: if (assign_ix is not None) \ and (len(line) >= assign_ix + 2) \ and (line[assign_ix+1].string == '%') \ and (line[assign_ix+2].type == tokenize.NAME): This statement contains four continued line pieces. Assembling these pieces into a single line would give:: if (assign_ix is not None) and (len(line) >= assign_ix + 2) and (line[... This uses 0-indexed line numbers. *start* is (lineno, colno). Used to allow ``%magic`` and ``!system`` commands to be continued over multiple lines. Here is the function: def assemble_continued_line(lines, start: Tuple[int, int], end_line: int): r"""Assemble a single line from multiple continued line pieces Continued lines are lines ending in ``\``, and the line following the last ``\`` in the block. For example, this code continues over multiple lines:: if (assign_ix is not None) \ and (len(line) >= assign_ix + 2) \ and (line[assign_ix+1].string == '%') \ and (line[assign_ix+2].type == tokenize.NAME): This statement contains four continued line pieces. Assembling these pieces into a single line would give:: if (assign_ix is not None) and (len(line) >= assign_ix + 2) and (line[... This uses 0-indexed line numbers. *start* is (lineno, colno). Used to allow ``%magic`` and ``!system`` commands to be continued over multiple lines. """ parts = [lines[start[0]][start[1]:]] + lines[start[0]+1:end_line+1] return ' '.join([p.rstrip()[:-1] for p in parts[:-1]] # Strip backslash+newline + [parts[-1].rstrip()]) # Strip newline from last line
r"""Assemble a single line from multiple continued line pieces Continued lines are lines ending in ``\``, and the line following the last ``\`` in the block. For example, this code continues over multiple lines:: if (assign_ix is not None) \ and (len(line) >= assign_ix + 2) \ and (line[assign_ix+1].string == '%') \ and (line[assign_ix+2].type == tokenize.NAME): This statement contains four continued line pieces. Assembling these pieces into a single line would give:: if (assign_ix is not None) and (len(line) >= assign_ix + 2) and (line[... This uses 0-indexed line numbers. *start* is (lineno, colno). Used to allow ``%magic`` and ``!system`` commands to be continued over multiple lines.
176,684
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings def _make_help_call(target, esc): """Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)""" method = 'pinfo2' if esc == '??' \ else 'psearch' if '*' in target \ else 'pinfo' arg = " ".join([method, target]) #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) t_magic_name, _, t_magic_arg_s = arg.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) return "get_ipython().run_line_magic(%r, %r)" % (t_magic_name, t_magic_arg_s) The provided code snippet includes necessary dependencies for implementing the `_tr_help` function. Write a Python function `def _tr_help(content)` to solve the following problem: Translate lines escaped with: ? A naked help line should fire the intro help screen (shell.show_usage()) Here is the function: def _tr_help(content): """Translate lines escaped with: ? A naked help line should fire the intro help screen (shell.show_usage()) """ if not content: return 'get_ipython().show_usage()' return _make_help_call(content, '?')
Translate lines escaped with: ? A naked help line should fire the intro help screen (shell.show_usage())
176,685
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings def _make_help_call(target, esc): """Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)""" method = 'pinfo2' if esc == '??' \ else 'psearch' if '*' in target \ else 'pinfo' arg = " ".join([method, target]) #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) t_magic_name, _, t_magic_arg_s = arg.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) return "get_ipython().run_line_magic(%r, %r)" % (t_magic_name, t_magic_arg_s) The provided code snippet includes necessary dependencies for implementing the `_tr_help2` function. Write a Python function `def _tr_help2(content)` to solve the following problem: Translate lines escaped with: ?? A naked help line should fire the intro help screen (shell.show_usage()) Here is the function: def _tr_help2(content): """Translate lines escaped with: ?? A naked help line should fire the intro help screen (shell.show_usage()) """ if not content: return 'get_ipython().show_usage()' return _make_help_call(content, '??')
Translate lines escaped with: ?? A naked help line should fire the intro help screen (shell.show_usage())
176,686
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings The provided code snippet includes necessary dependencies for implementing the `_tr_magic` function. Write a Python function `def _tr_magic(content)` to solve the following problem: Translate lines escaped with a percent sign: % Here is the function: def _tr_magic(content): "Translate lines escaped with a percent sign: %" name, _, args = content.partition(' ') return 'get_ipython().run_line_magic(%r, %r)' % (name, args)
Translate lines escaped with a percent sign: %
176,687
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings The provided code snippet includes necessary dependencies for implementing the `_tr_quote` function. Write a Python function `def _tr_quote(content)` to solve the following problem: Translate lines escaped with a comma: , Here is the function: def _tr_quote(content): "Translate lines escaped with a comma: ," name, _, args = content.partition(' ') return '%s("%s")' % (name, '", "'.join(args.split()) )
Translate lines escaped with a comma: ,
176,688
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings The provided code snippet includes necessary dependencies for implementing the `_tr_quote2` function. Write a Python function `def _tr_quote2(content)` to solve the following problem: Translate lines escaped with a semicolon: ; Here is the function: def _tr_quote2(content): "Translate lines escaped with a semicolon: ;" name, _, args = content.partition(' ') return '%s("%s")' % (name, args)
Translate lines escaped with a semicolon: ;
176,689
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings The provided code snippet includes necessary dependencies for implementing the `_tr_paren` function. Write a Python function `def _tr_paren(content)` to solve the following problem: Translate lines escaped with a slash: / Here is the function: def _tr_paren(content): "Translate lines escaped with a slash: /" name, _, args = content.partition(' ') return '%s(%s)' % (name, ", ".join(args.split()))
Translate lines escaped with a slash: /
176,690
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings List = _Alias() The provided code snippet includes necessary dependencies for implementing the `has_sunken_brackets` function. Write a Python function `def has_sunken_brackets(tokens: List[tokenize.TokenInfo])` to solve the following problem: Check if the depth of brackets in the list of tokens drops below 0 Here is the function: def has_sunken_brackets(tokens: List[tokenize.TokenInfo]): """Check if the depth of brackets in the list of tokens drops below 0""" parenlev = 0 for token in tokens: if token.string in {"(", "[", "{"}: parenlev += 1 elif token.string in {")", "]", "}"}: parenlev -= 1 if parenlev < 0: return True return False
Check if the depth of brackets in the list of tokens drops below 0
176,691
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings def make_tokens_by_line(lines:List[str]): """Tokenize a series of lines and group tokens by line. The tokens for a multiline Python string or expression are grouped as one line. All lines except the last lines should keep their line ending ('\\n', '\\r\\n') for this to properly work. Use `.splitlines(keeplineending=True)` for example when passing block of text to this function. """ # NL tokens are used inside multiline expressions, but also after blank # lines or comments. This is intentional - see https://bugs.python.org/issue17061 # We want to group the former case together but split the latter, so we # track parentheses level, similar to the internals of tokenize. # reexported from token on 3.7+ NEWLINE, NL = tokenize.NEWLINE, tokenize.NL # type: ignore tokens_by_line: List[List[Any]] = [[]] if len(lines) > 1 and not lines[0].endswith(("\n", "\r", "\r\n", "\x0b", "\x0c")): warnings.warn( "`make_tokens_by_line` received a list of lines which do not have lineending markers ('\\n', '\\r', '\\r\\n', '\\x0b', '\\x0c'), behavior will be unspecified", stacklevel=2, ) parenlev = 0 try: for token in tokenize.generate_tokens(iter(lines).__next__): tokens_by_line[-1].append(token) if (token.type == NEWLINE) \ or ((token.type == NL) and (parenlev <= 0)): tokens_by_line.append([]) elif token.string in {'(', '[', '{'}: parenlev += 1 elif token.string in {')', ']', '}'}: if parenlev > 0: parenlev -= 1 except tokenize.TokenError: # Input ended in a multiline string or expression. That's OK for us. pass if not tokens_by_line[-1]: tokens_by_line.pop() return tokens_by_line The provided code snippet includes necessary dependencies for implementing the `show_linewise_tokens` function. Write a Python function `def show_linewise_tokens(s: str)` to solve the following problem: For investigation and debugging Here is the function: def show_linewise_tokens(s: str): """For investigation and debugging""" warnings.warn( "show_linewise_tokens is deprecated since IPython 8.6", DeprecationWarning, stacklevel=2, ) if not s.endswith("\n"): s += "\n" lines = s.splitlines(keepends=True) for line in make_tokens_by_line(lines): print("Line -------") for tokinfo in line: print(" ", tokinfo)
For investigation and debugging
176,692
import ast from codeop import CommandCompiler, Compile import re import tokenize from typing import List, Tuple, Optional, Any import warnings _indent_re = re.compile(r'^[ \t]+') def find_last_indent(lines): m = _indent_re.match(lines[-1]) if not m: return 0 return len(m.group(0).replace('\t', ' '*4))
null
176,693
import inspect import linecache import sys import re import os from IPython import get_ipython from IPython.utils import PyColorize from IPython.utils import coloransi, py3compat from IPython.core.excolors import exception_colors from pdb import Pdb as OldPdb The provided code snippet includes necessary dependencies for implementing the `BdbQuit_excepthook` function. Write a Python function `def BdbQuit_excepthook(et, ev, tb, excepthook=None)` to solve the following problem: Exception hook which handles `BdbQuit` exceptions. All other exceptions are processed using the `excepthook` parameter. Here is the function: def BdbQuit_excepthook(et, ev, tb, excepthook=None): """Exception hook which handles `BdbQuit` exceptions. All other exceptions are processed using the `excepthook` parameter. """ raise ValueError( "`BdbQuit_excepthook` is deprecated since version 5.1", )
Exception hook which handles `BdbQuit` exceptions. All other exceptions are processed using the `excepthook` parameter.
176,694
import inspect import linecache import sys import re import os from IPython import get_ipython from IPython.utils import PyColorize from IPython.utils import coloransi, py3compat from IPython.core.excolors import exception_colors from pdb import Pdb as OldPdb def BdbQuit_IPython_excepthook(self, et, ev, tb, tb_offset=None): raise ValueError( "`BdbQuit_IPython_excepthook` is deprecated since version 5.1", DeprecationWarning, stacklevel=2)
null
176,695
import inspect import linecache import sys import re import os from IPython import get_ipython from IPython.utils import PyColorize from IPython.utils import coloransi, py3compat from IPython.core.excolors import exception_colors from pdb import Pdb as OldPdb def strip_indentation(multiline_string): return RGX_EXTRA_INDENT.sub('', multiline_string) The provided code snippet includes necessary dependencies for implementing the `decorate_fn_with_doc` function. Write a Python function `def decorate_fn_with_doc(new_fn, old_fn, additional_text="")` to solve the following problem: Make new_fn have old_fn's doc string. This is particularly useful for the ``do_...`` commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth. Here is the function: def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): """Make new_fn have old_fn's doc string. This is particularly useful for the ``do_...`` commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.""" def wrapper(*args, **kw): return new_fn(*args, **kw) if old_fn.__doc__: wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text return wrapper
Make new_fn have old_fn's doc string. This is particularly useful for the ``do_...`` commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.
176,696
import inspect import linecache import sys import re import os from IPython import get_ipython from IPython.utils import PyColorize from IPython.utils import coloransi, py3compat from IPython.core.excolors import exception_colors from pdb import Pdb as OldPdb class Pdb(OldPdb): """Modified Pdb class, does not load readline. for a standalone version that uses prompt_toolkit, see `IPython.terminal.debugger.TerminalPdb` and `IPython.terminal.debugger.set_trace()` This debugger can hide and skip frames that are tagged according to some predicates. See the `skip_predicates` commands. """ default_predicates = { "tbhide": True, "readonly": False, "ipython_internal": True, "debuggerskip": True, } def __init__(self, completekey=None, stdin=None, stdout=None, context=5, **kwargs): """Create a new IPython debugger. Parameters ---------- completekey : default None Passed to pdb.Pdb. stdin : default None Passed to pdb.Pdb. stdout : default None Passed to pdb.Pdb. context : int Number of lines of source code context to show when displaying stacktrace information. **kwargs Passed to pdb.Pdb. Notes ----- The possibilities are python version dependent, see the python docs for more info. """ # Parent constructor: try: self.context = int(context) if self.context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError) as e: raise ValueError("Context must be a positive integer") from e # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`. OldPdb.__init__(self, completekey, stdin, stdout, **kwargs) # IPython changes... self.shell = get_ipython() if self.shell is None: save_main = sys.modules['__main__'] # No IPython instance running, we must create one from IPython.terminal.interactiveshell import \ TerminalInteractiveShell self.shell = TerminalInteractiveShell.instance() # needed by any code which calls __import__("__main__") after # the debugger was entered. See also #9941. sys.modules["__main__"] = save_main color_scheme = self.shell.colors self.aliases = {} # Create color table: we copy the default one from the traceback # module and add a few attributes needed for debugging self.color_scheme_table = exception_colors() # shorthands C = coloransi.TermColors cst = self.color_scheme_table cst['NoColor'].colors.prompt = C.NoColor cst['NoColor'].colors.breakpoint_enabled = C.NoColor cst['NoColor'].colors.breakpoint_disabled = C.NoColor cst['Linux'].colors.prompt = C.Green cst['Linux'].colors.breakpoint_enabled = C.LightRed cst['Linux'].colors.breakpoint_disabled = C.Red cst['LightBG'].colors.prompt = C.Blue cst['LightBG'].colors.breakpoint_enabled = C.LightRed cst['LightBG'].colors.breakpoint_disabled = C.Red cst['Neutral'].colors.prompt = C.Blue cst['Neutral'].colors.breakpoint_enabled = C.LightRed cst['Neutral'].colors.breakpoint_disabled = C.Red # Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser(style=color_scheme) self.set_colors(color_scheme) # Set the prompt - the default prompt is '(Pdb)' self.prompt = prompt self.skip_hidden = True self.report_skipped = True # list of predicates we use to skip frames self._predicates = self.default_predicates # def set_colors(self, scheme): """Shorthand access to the color table scheme selector method.""" self.color_scheme_table.set_active_scheme(scheme) self.parser.style = scheme def set_trace(self, frame=None): if frame is None: frame = sys._getframe().f_back self.initial_frame = frame return super().set_trace(frame) def _hidden_predicate(self, frame): """ Given a frame return whether it it should be hidden or not by IPython. """ if self._predicates["readonly"]: fname = frame.f_code.co_filename # we need to check for file existence and interactively define # function would otherwise appear as RO. if os.path.isfile(fname) and not os.access(fname, os.W_OK): return True if self._predicates["tbhide"]: if frame in (self.curframe, getattr(self, "initial_frame", None)): return False frame_locals = self._get_frame_locals(frame) if "__tracebackhide__" not in frame_locals: return False return frame_locals["__tracebackhide__"] return False def hidden_frames(self, stack): """ Given an index in the stack return whether it should be skipped. This is used in up/down and where to skip frames. """ # The f_locals dictionary is updated from the actual frame # locals whenever the .f_locals accessor is called, so we # avoid calling it here to preserve self.curframe_locals. # Furthermore, there is no good reason to hide the current frame. ip_hide = [self._hidden_predicate(s[0]) for s in stack] ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"] if ip_start and self._predicates["ipython_internal"]: ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)] return ip_hide def interaction(self, frame, traceback): try: OldPdb.interaction(self, frame, traceback) except KeyboardInterrupt: self.stdout.write("\n" + self.shell.get_exception_only()) def precmd(self, line): """Perform useful escapes on the command before it is executed.""" if line.endswith("??"): line = "pinfo2 " + line[:-2] elif line.endswith("?"): line = "pinfo " + line[:-1] line = super().precmd(line) return line def new_do_frame(self, arg): OldPdb.do_frame(self, arg) def new_do_quit(self, arg): if hasattr(self, 'old_all_completions'): self.shell.Completer.all_completions = self.old_all_completions return OldPdb.do_quit(self, arg) do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) def new_do_restart(self, arg): """Restart command. In the context of ipython this is exactly the same thing as 'quit'.""" self.msg("Restart doesn't make sense here. Using 'quit' instead.") return self.do_quit(arg) def print_stack_trace(self, context=None): Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal if context is None: context = self.context try: context = int(context) if context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError) as e: raise ValueError("Context must be a positive integer") from e try: skipped = 0 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack): if hidden and self.skip_hidden: skipped += 1 continue if skipped: print( f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n" ) skipped = 0 self.print_stack_entry(frame_lineno, context=context) if skipped: print( f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n" ) except KeyboardInterrupt: pass def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ', context=None): if context is None: context = self.context try: context = int(context) if context <= 0: raise ValueError("Context must be a positive integer") except (TypeError, ValueError) as e: raise ValueError("Context must be a positive integer") from e print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout) # vds: >> frame, lineno = frame_lineno filename = frame.f_code.co_filename self.shell.hooks.synchronize_with_editor(filename, lineno, 0) # vds: << def _get_frame_locals(self, frame): """ " Accessing f_local of current frame reset the namespace, so we want to avoid that or the following can happen ipdb> foo "old" ipdb> foo = "new" ipdb> foo "new" ipdb> where ipdb> foo "old" So if frame is self.current_frame we instead return self.curframe_locals """ if frame is self.curframe: return self.curframe_locals else: return frame.f_locals def format_stack_entry(self, frame_lineno, lprefix=': ', context=None): if context is None: context = self.context try: context = int(context) if context <= 0: print("Context must be a positive integer", file=self.stdout) except (TypeError, ValueError): print("Context must be a positive integer", file=self.stdout) import reprlib ret = [] Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal) tpl_call = "%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal) tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal) tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal) frame, lineno = frame_lineno return_value = '' loc_frame = self._get_frame_locals(frame) if "__return__" in loc_frame: rv = loc_frame["__return__"] # return_value += '->' return_value += reprlib.repr(rv) + "\n" ret.append(return_value) #s = filename + '(' + `lineno` + ')' filename = self.canonic(frame.f_code.co_filename) link = tpl_link % py3compat.cast_unicode(filename) if frame.f_code.co_name: func = frame.f_code.co_name else: func = "<lambda>" call = "" if func != "?": if "__args__" in loc_frame: args = reprlib.repr(loc_frame["__args__"]) else: args = '()' call = tpl_call % (func, args) # The level info should be generated in the same format pdb uses, to # avoid breaking the pdbtrack functionality of python-mode in *emacs. if frame is self.curframe: ret.append('> ') else: ret.append(" ") ret.append("%s(%s)%s\n" % (link, lineno, call)) start = lineno - 1 - context//2 lines = linecache.getlines(filename) start = min(start, len(lines) - context) start = max(start, 0) lines = lines[start : start + context] for i, line in enumerate(lines): show_arrow = start + 1 + i == lineno linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line ret.append( self.__format_line( linetpl, filename, start + 1 + i, line, arrow=show_arrow ) ) return "".join(ret) def __format_line(self, tpl_line, filename, lineno, line, arrow=False): bp_mark = "" bp_mark_color = "" new_line, err = self.parser.format2(line, 'str') if not err: line = new_line bp = None if lineno in self.get_file_breaks(filename): bps = self.get_breaks(filename, lineno) bp = bps[-1] if bp: Colors = self.color_scheme_table.active_colors bp_mark = str(bp.number) bp_mark_color = Colors.breakpoint_enabled if not bp.enabled: bp_mark_color = Colors.breakpoint_disabled numbers_width = 7 if arrow: # This is the line with the error pad = numbers_width - len(str(lineno)) - len(bp_mark) num = '%s%s' % (make_arrow(pad), str(lineno)) else: num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) return tpl_line % (bp_mark_color + bp_mark, num, line) def print_list_lines(self, filename, first, last): """The printing (as opposed to the parsing part of a 'list' command.""" try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) src = [] if filename == "<string>" and hasattr(self, "_exec_filename"): filename = self._exec_filename for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: break if lineno == self.curframe.f_lineno: line = self.__format_line( tpl_line_em, filename, lineno, line, arrow=True ) else: line = self.__format_line( tpl_line, filename, lineno, line, arrow=False ) src.append(line) self.lineno = lineno print(''.join(src), file=self.stdout) except KeyboardInterrupt: pass def do_skip_predicates(self, args): """ Turn on/off individual predicates as to whether a frame should be hidden/skip. The global option to skip (or not) hidden frames is set with skip_hidden To change the value of a predicate skip_predicates key [true|false] Call without arguments to see the current values. To permanently change the value of an option add the corresponding command to your ``~/.pdbrc`` file. If you are programmatically using the Pdb instance you can also change the ``default_predicates`` class attribute. """ if not args.strip(): print("current predicates:") for p, v in self._predicates.items(): print(" ", p, ":", v) return type_value = args.strip().split(" ") if len(type_value) != 2: print( f"Usage: skip_predicates <type> <value>, with <type> one of {set(self._predicates.keys())}" ) return type_, value = type_value if type_ not in self._predicates: print(f"{type_!r} not in {set(self._predicates.keys())}") return if value.lower() not in ("true", "yes", "1", "no", "false", "0"): print( f"{value!r} is invalid - use one of ('true', 'yes', '1', 'no', 'false', '0')" ) return self._predicates[type_] = value.lower() in ("true", "yes", "1") if not any(self._predicates.values()): print( "Warning, all predicates set to False, skip_hidden may not have any effects." ) def do_skip_hidden(self, arg): """ Change whether or not we should skip frames with the __tracebackhide__ attribute. """ if not arg.strip(): print( f"skip_hidden = {self.skip_hidden}, use 'yes','no', 'true', or 'false' to change." ) elif arg.strip().lower() in ("true", "yes"): self.skip_hidden = True elif arg.strip().lower() in ("false", "no"): self.skip_hidden = False if not any(self._predicates.values()): print( "Warning, all predicates set to False, skip_hidden may not have any effects." ) def do_list(self, arg): """Print lines of code from the current stack frame """ self.lastcmd = 'list' last = None if arg: try: x = eval(arg, {}, {}) if type(x) == type(()): first, last = x first = int(first) last = int(last) if last < first: # Assume it's a count last = first + last else: first = max(1, int(x) - 5) except: print('*** Error in argument:', repr(arg), file=self.stdout) return elif self.lineno is None: first = max(1, self.curframe.f_lineno - 5) else: first = self.lineno + 1 if last is None: last = first + 10 self.print_list_lines(self.curframe.f_code.co_filename, first, last) # vds: >> lineno = first filename = self.curframe.f_code.co_filename self.shell.hooks.synchronize_with_editor(filename, lineno, 0) # vds: << do_l = do_list def getsourcelines(self, obj): lines, lineno = inspect.findsource(obj) if inspect.isframe(obj) and obj.f_globals is self._get_frame_locals(obj): # must be a module frame: do not try to cut a block out of it return lines, 1 elif inspect.ismodule(obj): return lines, 1 return inspect.getblock(lines[lineno:]), lineno+1 def do_longlist(self, arg): """Print lines of code from the current stack frame. Shows more lines than 'list' does. """ self.lastcmd = 'longlist' try: lines, lineno = self.getsourcelines(self.curframe) except OSError as err: self.error(err) return last = lineno + len(lines) self.print_list_lines(self.curframe.f_code.co_filename, lineno, last) do_ll = do_longlist def do_debug(self, arg): """debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment). """ trace_function = sys.gettrace() sys.settrace(None) globals = self.curframe.f_globals locals = self.curframe_locals p = self.__class__(completekey=self.completekey, stdin=self.stdin, stdout=self.stdout) p.use_rawinput = self.use_rawinput p.prompt = "(%s) " % self.prompt.strip() self.message("ENTERING RECURSIVE DEBUGGER") sys.call_tracing(p.run, (arg, globals, locals)) self.message("LEAVING RECURSIVE DEBUGGER") sys.settrace(trace_function) self.lastcmd = p.lastcmd def do_pdef(self, arg): """Print the call signature for any callable object. The debugger interface to %pdef""" namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("pdef")(arg, namespaces=namespaces) def do_pdoc(self, arg): """Print the docstring for an object. The debugger interface to %pdoc.""" namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces) def do_pfile(self, arg): """Print (or run through pager) the file where an object is defined. The debugger interface to %pfile. """ namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("pfile")(arg, namespaces=namespaces) def do_pinfo(self, arg): """Provide detailed information about an object. The debugger interface to %pinfo, i.e., obj?.""" namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces) def do_pinfo2(self, arg): """Provide extra detailed information about an object. The debugger interface to %pinfo2, i.e., obj??.""" namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces) def do_psource(self, arg): """Print (or run through pager) the source code for an object.""" namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("psource")(arg, namespaces=namespaces) def do_where(self, arg): """w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the "current frame", which determines the context of most commands. 'bt' is an alias for this command. Take a number as argument as an (optional) number of context line to print""" if arg: try: context = int(arg) except ValueError as err: self.error(err) return self.print_stack_trace(context) else: self.print_stack_trace() do_w = do_where def break_anywhere(self, frame): """ _stop_in_decorator_internals is overly restrictive, as we may still want to trace function calls, so we need to also update break_anywhere so that is we don't `stop_here`, because of debugger skip, we may still stop at any point inside the function """ sup = super().break_anywhere(frame) if sup: return sup if self._predicates["debuggerskip"]: if DEBUGGERSKIP in frame.f_code.co_varnames: return True if frame.f_back and self._get_frame_locals(frame.f_back).get(DEBUGGERSKIP): return True return False def _is_in_decorator_internal_and_should_skip(self, frame): """ Utility to tell us whether we are in a decorator internal and should stop. """ # if we are disabled don't skip if not self._predicates["debuggerskip"]: return False # if frame is tagged, skip by default. if DEBUGGERSKIP in frame.f_code.co_varnames: return True # if one of the parent frame value set to True skip as well. cframe = frame while getattr(cframe, "f_back", None): cframe = cframe.f_back if self._get_frame_locals(cframe).get(DEBUGGERSKIP): return True return False def stop_here(self, frame): if self._is_in_decorator_internal_and_should_skip(frame) is True: return False hidden = False if self.skip_hidden: hidden = self._hidden_predicate(frame) if hidden: if self.report_skipped: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal print( f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n" ) return super().stop_here(frame) def do_up(self, arg): """u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). Will skip hidden frames. """ # modified version of upstream that skips # frames with __tracebackhide__ if self.curindex == 0: self.error("Oldest frame") return try: count = int(arg or 1) except ValueError: self.error("Invalid frame count (%s)" % arg) return skipped = 0 if count < 0: _newframe = 0 else: counter = 0 hidden_frames = self.hidden_frames(self.stack) for i in range(self.curindex - 1, -1, -1): if hidden_frames[i] and self.skip_hidden: skipped += 1 continue counter += 1 if counter >= count: break else: # if no break occurred. self.error( "all frames above hidden, use `skip_hidden False` to get get into those." ) return Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal _newframe = i self._select_frame(_newframe) if skipped: print( f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n" ) def do_down(self, arg): """d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame). Will skip hidden frames. """ if self.curindex + 1 == len(self.stack): self.error("Newest frame") return try: count = int(arg or 1) except ValueError: self.error("Invalid frame count (%s)" % arg) return if count < 0: _newframe = len(self.stack) - 1 else: counter = 0 skipped = 0 hidden_frames = self.hidden_frames(self.stack) for i in range(self.curindex + 1, len(self.stack)): if hidden_frames[i] and self.skip_hidden: skipped += 1 continue counter += 1 if counter >= count: break else: self.error( "all frames below hidden, use `skip_hidden False` to get get into those." ) return Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal if skipped: print( f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n" ) _newframe = i self._select_frame(_newframe) do_d = do_down do_u = do_up def do_context(self, context): """context number_of_lines Set the number of lines of source code to show when displaying stacktrace information. """ try: new_context = int(context) if new_context <= 0: raise ValueError() self.context = new_context except ValueError: self.error("The 'context' command requires a positive integer argument.") import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False class Pdb(Bdb, Cmd): # Everything here is undocumented, except for __init__ commands_resuming: ClassVar[List[str]] aliases: Dict[str, str] mainpyfile: str _wait_for_mainpyfile: bool rcLines: List[str] commands: Dict[int, List[str]] commands_doprompt: Dict[int, bool] commands_silent: Dict[int, bool] commands_defining: bool commands_bnum: Optional[int] lineno: Optional[int] stack: List[Tuple[FrameType, int]] curindex: int curframe: Optional[FrameType] curframe_locals: Mapping[str, Any] if sys.version_info >= (3, 6): def __init__( self, completekey: str = ..., stdin: Optional[IO[str]] = ..., stdout: Optional[IO[str]] = ..., skip: Optional[Iterable[str]] = ..., nosigint: bool = ..., readrc: bool = ..., ) -> None: ... elif sys.version_info >= (3, 2): def __init__( self, completekey: str = ..., stdin: Optional[IO[str]] = ..., stdout: Optional[IO[str]] = ..., skip: Optional[Iterable[str]] = ..., nosigint: bool = ..., ) -> None: ... else: def __init__( self, completekey: str = ..., stdin: Optional[IO[str]] = ..., stdout: Optional[IO[str]] = ..., skip: Optional[Iterable[str]] = ..., ) -> None: ... def forget(self) -> None: ... def setup(self, f: Optional[FrameType], tb: Optional[TracebackType]) -> None: ... def execRcLines(self) -> None: ... def bp_commands(self, frame: FrameType) -> bool: ... def interaction(self, frame: Optional[FrameType], traceback: Optional[TracebackType]) -> None: ... def displayhook(self, obj: object) -> None: ... def handle_command_def(self, line: str) -> bool: ... def defaultFile(self) -> str: ... def lineinfo(self, identifier: str) -> Union[Tuple[None, None, None], Tuple[str, str, int]]: ... def checkline(self, filename: str, lineno: int) -> int: ... def _getval(self, arg: str) -> object: ... def print_stack_trace(self) -> None: ... def print_stack_entry(self, frame_lineno: Tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... def lookupmodule(self, filename: str) -> Optional[str]: ... def _runscript(self, filename: str) -> None: ... def do_commands(self, arg: str) -> Optional[bool]: ... def do_break(self, arg: str, temporary: bool = ...) -> Optional[bool]: ... def do_tbreak(self, arg: str) -> Optional[bool]: ... def do_enable(self, arg: str) -> Optional[bool]: ... def do_disable(self, arg: str) -> Optional[bool]: ... def do_condition(self, arg: str) -> Optional[bool]: ... def do_ignore(self, arg: str) -> Optional[bool]: ... def do_clear(self, arg: str) -> Optional[bool]: ... def do_where(self, arg: str) -> Optional[bool]: ... def do_up(self, arg: str) -> Optional[bool]: ... def do_down(self, arg: str) -> Optional[bool]: ... def do_until(self, arg: str) -> Optional[bool]: ... def do_step(self, arg: str) -> Optional[bool]: ... def do_next(self, arg: str) -> Optional[bool]: ... def do_run(self, arg: str) -> Optional[bool]: ... def do_return(self, arg: str) -> Optional[bool]: ... def do_continue(self, arg: str) -> Optional[bool]: ... def do_jump(self, arg: str) -> Optional[bool]: ... def do_debug(self, arg: str) -> Optional[bool]: ... def do_quit(self, arg: str) -> Optional[bool]: ... def do_EOF(self, arg: str) -> Optional[bool]: ... def do_args(self, arg: str) -> Optional[bool]: ... def do_retval(self, arg: str) -> Optional[bool]: ... def do_p(self, arg: str) -> Optional[bool]: ... def do_pp(self, arg: str) -> Optional[bool]: ... def do_list(self, arg: str) -> Optional[bool]: ... def do_whatis(self, arg: str) -> Optional[bool]: ... def do_alias(self, arg: str) -> Optional[bool]: ... def do_unalias(self, arg: str) -> Optional[bool]: ... def do_help(self, arg: str) -> Optional[bool]: ... do_b = do_break do_cl = do_clear do_w = do_where do_bt = do_where do_u = do_up do_d = do_down do_unt = do_until do_s = do_step do_n = do_next do_restart = do_run do_r = do_return do_c = do_continue do_cont = do_continue do_j = do_jump do_q = do_quit do_exit = do_quit do_a = do_args do_rv = do_retval do_l = do_list do_h = do_help def help_exec(self) -> None: ... def help_pdb(self) -> None: ... if sys.version_info < (3, 2): def help_help(self) -> None: ... def help_h(self) -> None: ... def help_where(self) -> None: ... def help_w(self) -> None: ... def help_down(self) -> None: ... def help_d(self) -> None: ... def help_up(self) -> None: ... def help_u(self) -> None: ... def help_break(self) -> None: ... def help_b(self) -> None: ... def help_clear(self) -> None: ... def help_cl(self) -> None: ... def help_tbreak(self) -> None: ... def help_enable(self) -> None: ... def help_disable(self) -> None: ... def help_ignore(self) -> None: ... def help_condition(self) -> None: ... def help_step(self) -> None: ... def help_s(self) -> None: ... def help_until(self) -> None: ... def help_unt(self) -> None: ... def help_next(self) -> None: ... def help_n(self) -> None: ... def help_return(self) -> None: ... def help_r(self) -> None: ... def help_continue(self) -> None: ... def help_cont(self) -> None: ... def help_c(self) -> None: ... def help_jump(self) -> None: ... def help_j(self) -> None: ... def help_debug(self) -> None: ... def help_list(self) -> None: ... def help_l(self) -> None: ... def help_args(self) -> None: ... def help_a(self) -> None: ... def help_p(self) -> None: ... def help_pp(self) -> None: ... def help_run(self) -> None: ... def help_quit(self) -> None: ... def help_q(self) -> None: ... def help_whatis(self) -> None: ... def help_EOF(self) -> None: ... def help_alias(self) -> None: ... def help_unalias(self) -> None: ... def help_commands(self) -> None: ... help_bt = help_w help_restart = help_run help_exit = help_q if sys.version_info >= (3, 2): def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ... def message(self, msg: str) -> None: ... def error(self, msg: str) -> None: ... def _select_frame(self, number: int) -> None: ... def _getval_except(self, arg: str, frame: Optional[FrameType] = ...) -> object: ... def _print_lines( self, lines: Sequence[str], start: int, breaks: Sequence[int] = ..., frame: Optional[FrameType] = ... ) -> None: ... def _cmdloop(self) -> None: ... def do_display(self, arg: str) -> Optional[bool]: ... def do_interact(self, arg: str) -> Optional[bool]: ... def do_longlist(self, arg: str) -> Optional[bool]: ... def do_source(self, arg: str) -> Optional[bool]: ... def do_undisplay(self, arg: str) -> Optional[bool]: ... do_ll = do_longlist if sys.version_info >= (3, 3): def _complete_location(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... def _complete_bpnumber(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... def _complete_expression(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... def complete_undisplay(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... def complete_unalias(self, text: str, line: str, begidx: int, endidx: int) -> List[str]: ... complete_commands = _complete_bpnumber complete_break = _complete_location complete_b = _complete_location complete_tbreak = _complete_location complete_enable = _complete_bpnumber complete_disable = _complete_bpnumber complete_condition = _complete_bpnumber complete_ignore = _complete_bpnumber complete_clear = _complete_location complete_cl = _complete_location complete_debug = _complete_expression complete_print = _complete_expression complete_p = _complete_expression complete_pp = _complete_expression complete_source = _complete_expression complete_whatis = _complete_expression complete_display = _complete_expression if sys.version_info >= (3, 7): def _runmodule(self, module_name: str) -> None: ... if sys.version_info >= (3,) and sys.version_info < (3, 4): do_print = do_p The provided code snippet includes necessary dependencies for implementing the `set_trace` function. Write a Python function `def set_trace(frame=None)` to solve the following problem: Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. Here is the function: def set_trace(frame=None): """ Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """ Pdb().set_trace(frame or sys._getframe().f_back)
Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame.
176,697
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo def has_comment(src): """Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- comment : bool True if source has a comment. """ return (tokenize.COMMENT in _line_tokens(src)) The provided code snippet includes necessary dependencies for implementing the `assemble_logical_lines` function. Write a Python function `def assemble_logical_lines()` to solve the following problem: r"""Join lines following explicit line continuations (\) Here is the function: def assemble_logical_lines(): r"""Join lines following explicit line continuations (\)""" line = '' while True: line = (yield line) if not line or line.isspace(): continue parts = [] while line is not None: if line.endswith('\\') and (not has_comment(line)): parts.append(line[:-1]) line = (yield None) # Get another line else: parts.append(line) break # Output line = ''.join(parts)
r"""Join lines following explicit line continuations (\)
176,698
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo ESC_SHELL = '!' The provided code snippet includes necessary dependencies for implementing the `_tr_system` function. Write a Python function `def _tr_system(line_info)` to solve the following problem: Translate lines escaped with: ! Here is the function: def _tr_system(line_info): "Translate lines escaped with: !" cmd = line_info.line.lstrip().lstrip(ESC_SHELL) return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
Translate lines escaped with: !
176,699
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo The provided code snippet includes necessary dependencies for implementing the `_tr_system2` function. Write a Python function `def _tr_system2(line_info)` to solve the following problem: Translate lines escaped with: !! Here is the function: def _tr_system2(line_info): "Translate lines escaped with: !!" cmd = line_info.line.lstrip()[2:] return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
Translate lines escaped with: !!
176,700
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo def _make_help_call(target, esc, lspace): """Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)""" method = 'pinfo2' if esc == '??' \ else 'psearch' if '*' in target \ else 'pinfo' arg = " ".join([method, target]) #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) t_magic_name, _, t_magic_arg_s = arg.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) return "%sget_ipython().run_line_magic(%r, %r)" % ( lspace, t_magic_name, t_magic_arg_s, ) The provided code snippet includes necessary dependencies for implementing the `_tr_help` function. Write a Python function `def _tr_help(line_info)` to solve the following problem: Translate lines escaped with: ?/?? Here is the function: def _tr_help(line_info): "Translate lines escaped with: ?/??" # A naked help line should just fire the intro help screen if not line_info.line[1:]: return 'get_ipython().show_usage()' return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
Translate lines escaped with: ?/??
176,701
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo ESC_MAGIC = '%' ESC_MAGIC2 = '%%' The provided code snippet includes necessary dependencies for implementing the `_tr_magic` function. Write a Python function `def _tr_magic(line_info)` to solve the following problem: Translate lines escaped with: % Here is the function: def _tr_magic(line_info): "Translate lines escaped with: %" tpl = '%sget_ipython().run_line_magic(%r, %r)' if line_info.line.startswith(ESC_MAGIC2): return line_info.line cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip() #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) t_magic_name, _, t_magic_arg_s = cmd.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)
Translate lines escaped with: %
176,702
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo The provided code snippet includes necessary dependencies for implementing the `_tr_quote` function. Write a Python function `def _tr_quote(line_info)` to solve the following problem: Translate lines escaped with: , Here is the function: def _tr_quote(line_info): "Translate lines escaped with: ," return '%s%s("%s")' % (line_info.pre, line_info.ifun, '", "'.join(line_info.the_rest.split()) )
Translate lines escaped with: ,
176,703
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo The provided code snippet includes necessary dependencies for implementing the `_tr_quote2` function. Write a Python function `def _tr_quote2(line_info)` to solve the following problem: Translate lines escaped with: ; Here is the function: def _tr_quote2(line_info): "Translate lines escaped with: ;" return '%s%s("%s")' % (line_info.pre, line_info.ifun, line_info.the_rest)
Translate lines escaped with: ;
176,704
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo The provided code snippet includes necessary dependencies for implementing the `_tr_paren` function. Write a Python function `def _tr_paren(line_info)` to solve the following problem: Translate lines escaped with: / Here is the function: def _tr_paren(line_info): "Translate lines escaped with: /" return '%s%s(%s)' % (line_info.pre, line_info.ifun, ", ".join(line_info.the_rest.split()))
Translate lines escaped with: /
176,705
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo tr = { ESC_SHELL : _tr_system, ESC_SH_CAP : _tr_system2, ESC_HELP : _tr_help, ESC_HELP2 : _tr_help, ESC_MAGIC : _tr_magic, ESC_QUOTE : _tr_quote, ESC_QUOTE2 : _tr_quote2, ESC_PAREN : _tr_paren } class LineInfo(object): """A single line of input and associated info. Includes the following as properties: line The original, raw line continue_prompt Is this line a continuation in a sequence of multiline input? pre Any leading whitespace. esc The escape character(s) in pre or the empty string if there isn't one. Note that '!!' and '??' are possible values for esc. Otherwise it will always be a single character. ifun The 'function part', which is basically the maximal initial sequence of valid python identifiers and the '.' character. This is what is checked for alias and magic transformations, used for auto-calling, etc. In contrast to Python identifiers, it may start with "%" and contain "*". the_rest Everything else on the line. """ def __init__(self, line, continue_prompt=False): self.line = line self.continue_prompt = continue_prompt self.pre, self.esc, self.ifun, self.the_rest = split_user_input(line) self.pre_char = self.pre.strip() if self.pre_char: self.pre_whitespace = '' # No whitespace allowed before esc chars else: self.pre_whitespace = self.pre def ofind(self, ip) -> OInfo: """Do a full, attribute-walking lookup of the ifun in the various namespaces for the given IPython InteractiveShell instance. Return a dict with keys: {found, obj, ospace, ismagic} Note: can cause state changes because of calling getattr, but should only be run if autocall is on and if the line hasn't matched any other, less dangerous handlers. Does cache the results of the call, so can be called multiple times without worrying about *further* damaging state. """ return ip._ofind(self.ifun) def __str__(self): return "LineInfo [%s|%s|%s|%s]" %(self.pre, self.esc, self.ifun, self.the_rest) The provided code snippet includes necessary dependencies for implementing the `escaped_commands` function. Write a Python function `def escaped_commands(line)` to solve the following problem: Transform escaped commands - %magic, !system, ?help + various autocalls. Here is the function: def escaped_commands(line): """Transform escaped commands - %magic, !system, ?help + various autocalls. """ if not line or line.isspace(): return line lineinf = LineInfo(line) if lineinf.esc not in tr: return line return tr[lineinf.esc](lineinf)
Transform escaped commands - %magic, !system, ?help + various autocalls.
176,706
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo def _make_help_call(target, esc, lspace): """Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)""" method = 'pinfo2' if esc == '??' \ else 'psearch' if '*' in target \ else 'pinfo' arg = " ".join([method, target]) #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) t_magic_name, _, t_magic_arg_s = arg.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) return "%sget_ipython().run_line_magic(%r, %r)" % ( lspace, t_magic_name, t_magic_arg_s, ) _initial_space_re = re.compile(r'\s*') _help_end_re = re.compile(r"""(%{0,2} (?!\d)[\w*]+ # Variable name (\.(?!\d)[\w*]+)* # .etc.etc ) (\?\??)$ # ? or ?? """, re.VERBOSE) def ends_in_comment_or_string(src): """Indicates whether or not an input line ends in a comment or within a multiline string. Parameters ---------- src : string A single line input string. Returns ------- comment : bool True if source ends in a comment or multiline string. """ toktypes = _line_tokens(src) return (tokenize.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes) The provided code snippet includes necessary dependencies for implementing the `help_end` function. Write a Python function `def help_end(line)` to solve the following problem: Translate lines with ?/?? at the end Here is the function: def help_end(line): """Translate lines with ?/?? at the end""" m = _help_end_re.search(line) if m is None or ends_in_comment_or_string(line): return line target = m.group(1) esc = m.group(3) lspace = _initial_space_re.match(line).group(0) return _make_help_call(target, esc, lspace)
Translate lines with ?/?? at the end
176,707
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo ESC_MAGIC2 = '%%' The provided code snippet includes necessary dependencies for implementing the `cellmagic` function. Write a Python function `def cellmagic(end_on_blank_line=False)` to solve the following problem: Captures & transforms cell magics. After a cell magic is started, this stores up any lines it gets until it is reset (sent None). Here is the function: def cellmagic(end_on_blank_line=False): """Captures & transforms cell magics. After a cell magic is started, this stores up any lines it gets until it is reset (sent None). """ tpl = 'get_ipython().run_cell_magic(%r, %r, %r)' cellmagic_help_re = re.compile(r'%%\w+\?') line = '' while True: line = (yield line) # consume leading empty lines while not line: line = (yield line) if not line.startswith(ESC_MAGIC2): # This isn't a cell magic, idle waiting for reset then start over while line is not None: line = (yield line) continue if cellmagic_help_re.match(line): # This case will be handled by help_end continue first = line body = [] line = (yield None) while (line is not None) and \ ((line.strip() != '') or not end_on_blank_line): body.append(line) line = (yield None) # Output magic_name, _, first = first.partition(' ') magic_name = magic_name.lstrip(ESC_MAGIC2) line = tpl % (magic_name, first, u'\n'.join(body))
Captures & transforms cell magics. After a cell magic is started, this stores up any lines it gets until it is reset (sent None).
176,708
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None): """Remove matching input prompts from a block of input. Parameters ---------- prompt_re : regular expression A regular expression matching any input prompt (including continuation) initial_re : regular expression, optional A regular expression matching only the initial prompt, but not continuation. If no initial expression is given, prompt_re will be used everywhere. Used mainly for plain Python prompts, where the continuation prompt ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. Notes ----- If `initial_re` and `prompt_re differ`, only `initial_re` will be tested against the first line. If any prompt is found on the first two lines, prompts will be stripped from the rest of the block. """ if initial_re is None: initial_re = prompt_re line = '' while True: line = (yield line) # First line of cell if line is None: continue out, n1 = initial_re.subn('', line, count=1) if turnoff_re and not n1: if turnoff_re.match(line): # We're in e.g. a cell magic; disable this transformer for # the rest of the cell. while line is not None: line = (yield line) continue line = (yield out) if line is None: continue # check for any prompt on the second line of the cell, # because people often copy from just after the first prompt, # so we might not see it in the first line. out, n2 = prompt_re.subn('', line, count=1) line = (yield out) if n1 or n2: # Found a prompt in the first two lines - check for it in # the rest of the cell as well. while line is not None: line = (yield prompt_re.sub('', line, count=1)) else: # Prompts not in input - wait for reset while line is not None: line = (yield line) The provided code snippet includes necessary dependencies for implementing the `classic_prompt` function. Write a Python function `def classic_prompt()` to solve the following problem: Strip the >>>/... prompts of the Python interactive shell. Here is the function: def classic_prompt(): """Strip the >>>/... prompts of the Python interactive shell.""" # FIXME: non-capturing version (?:...) usable? prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)') initial_re = re.compile(r'^>>>( |$)') # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts turnoff_re = re.compile(r'^[%!]') return _strip_prompts(prompt_re, initial_re, turnoff_re)
Strip the >>>/... prompts of the Python interactive shell.
176,709
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None): """Remove matching input prompts from a block of input. Parameters ---------- prompt_re : regular expression A regular expression matching any input prompt (including continuation) initial_re : regular expression, optional A regular expression matching only the initial prompt, but not continuation. If no initial expression is given, prompt_re will be used everywhere. Used mainly for plain Python prompts, where the continuation prompt ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. Notes ----- If `initial_re` and `prompt_re differ`, only `initial_re` will be tested against the first line. If any prompt is found on the first two lines, prompts will be stripped from the rest of the block. """ if initial_re is None: initial_re = prompt_re line = '' while True: line = (yield line) # First line of cell if line is None: continue out, n1 = initial_re.subn('', line, count=1) if turnoff_re and not n1: if turnoff_re.match(line): # We're in e.g. a cell magic; disable this transformer for # the rest of the cell. while line is not None: line = (yield line) continue line = (yield out) if line is None: continue # check for any prompt on the second line of the cell, # because people often copy from just after the first prompt, # so we might not see it in the first line. out, n2 = prompt_re.subn('', line, count=1) line = (yield out) if n1 or n2: # Found a prompt in the first two lines - check for it in # the rest of the cell as well. while line is not None: line = (yield prompt_re.sub('', line, count=1)) else: # Prompts not in input - wait for reset while line is not None: line = (yield line) The provided code snippet includes necessary dependencies for implementing the `ipy_prompt` function. Write a Python function `def ipy_prompt()` to solve the following problem: Strip IPython's In [1]:/...: prompts. Here is the function: def ipy_prompt(): """Strip IPython's In [1]:/...: prompts.""" # FIXME: non-capturing version (?:...) usable? prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)') # Disable prompt stripping inside cell magics turnoff_re = re.compile(r'^%%') return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
Strip IPython's In [1]:/...: prompts.
176,710
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo The provided code snippet includes necessary dependencies for implementing the `leading_indent` function. Write a Python function `def leading_indent()` to solve the following problem: Remove leading indentation. If the first line starts with a spaces or tabs, the same whitespace will be removed from each following line until it is reset. Here is the function: def leading_indent(): """Remove leading indentation. If the first line starts with a spaces or tabs, the same whitespace will be removed from each following line until it is reset. """ space_re = re.compile(r'^[ \t]+') line = '' while True: line = (yield line) if line is None: continue m = space_re.match(line) if m: space = m.group(0) while line is not None: if line.startswith(space): line = line[len(space):] line = (yield line) else: # No leading spaces - wait for reset while line is not None: line = (yield line)
Remove leading indentation. If the first line starts with a spaces or tabs, the same whitespace will be removed from each following line until it is reset.
176,711
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE) assign_system_template = '%s = get_ipython().getoutput(%r)' The provided code snippet includes necessary dependencies for implementing the `assign_from_system` function. Write a Python function `def assign_from_system(line)` to solve the following problem: Transform assignment from system commands (e.g. files = !ls) Here is the function: def assign_from_system(line): """Transform assignment from system commands (e.g. files = !ls)""" m = assign_system_re.match(line) if m is None: return line return assign_system_template % m.group('lhs', 'cmd')
Transform assignment from system commands (e.g. files = !ls)
176,712
import abc import functools import re import tokenize from tokenize import generate_tokens, untokenize, TokenError from io import StringIO from IPython.core.splitinput import LineInfo ESC_MAGIC = '%' assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE) assign_magic_template = '%s = get_ipython().run_line_magic(%r, %r)' The provided code snippet includes necessary dependencies for implementing the `assign_from_magic` function. Write a Python function `def assign_from_magic(line)` to solve the following problem: Transform assignment from magic commands (e.g. a = %who_ls) Here is the function: def assign_from_magic(line): """Transform assignment from magic commands (e.g. a = %who_ls)""" m = assign_magic_re.match(line) if m is None: return line #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) m_lhs, m_cmd = m.group('lhs', 'cmd') t_magic_name, _, t_magic_arg_s = m_cmd.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) return assign_magic_template % (m_lhs, t_magic_name, t_magic_arg_s)
Transform assignment from magic commands (e.g. a = %who_ls)
176,713
import argparse import re from IPython.core.error import UsageError from IPython.utils.decorators import undoc from IPython.utils.process import arg_split from IPython.utils.text import dedent class MagicArgumentParser(argparse.ArgumentParser): """ An ArgumentParser tweaked for use by IPython magics. """ def __init__(self, prog=None, usage=None, description=None, epilog=None, parents=None, formatter_class=MagicHelpFormatter, prefix_chars='-', argument_default=None, conflict_handler='error', add_help=False): if parents is None: parents = [] super(MagicArgumentParser, self).__init__(prog=prog, usage=usage, description=description, epilog=epilog, parents=parents, formatter_class=formatter_class, prefix_chars=prefix_chars, argument_default=argument_default, conflict_handler=conflict_handler, add_help=add_help) def error(self, message): """ Raise a catchable error instead of exiting. """ raise UsageError(message) def parse_argstring(self, argstring): """ Split a string into an argument list and parse that argument list. """ argv = arg_split(argstring) return self.parse_args(argv) def real_name(magic_func): """ Find the real name of the magic. """ magic_name = magic_func.__name__ if magic_name.startswith('magic_'): magic_name = magic_name[len('magic_'):] return getattr(magic_func, 'argcmd_name', magic_name) class kwds(ArgDecorator): """ Provide other keywords to the sub-parser constructor. """ def __init__(self, **kwds): self.kwds = kwds def __call__(self, func): func = super(kwds, self).__call__(func) func.argcmd_kwds = self.kwds return func The provided code snippet includes necessary dependencies for implementing the `construct_parser` function. Write a Python function `def construct_parser(magic_func)` to solve the following problem: Construct an argument parser using the function decorations. Here is the function: def construct_parser(magic_func): """ Construct an argument parser using the function decorations. """ kwds = getattr(magic_func, 'argcmd_kwds', {}) if 'description' not in kwds: kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) # Reverse the list of decorators in order to apply them in the # order in which they appear in the source. group = None for deco in magic_func.decorators[::-1]: result = deco.add_to_parser(parser, group) if result is not None: group = result # Replace the magic function's docstring with the full help text. magic_func.__doc__ = parser.format_help() return parser
Construct an argument parser using the function decorations.
176,714
import argparse import re from IPython.core.error import UsageError from IPython.utils.decorators import undoc from IPython.utils.process import arg_split from IPython.utils.text import dedent The provided code snippet includes necessary dependencies for implementing the `parse_argstring` function. Write a Python function `def parse_argstring(magic_func, argstring)` to solve the following problem: Parse the string of arguments for the given magic function. Here is the function: def parse_argstring(magic_func, argstring): """ Parse the string of arguments for the given magic function. """ return magic_func.parser.parse_argstring(argstring)
Parse the string of arguments for the given magic function.
176,715
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions _deprecated_names = ["display", "clear_output", "publish_display_data", "update_display", "DisplayHandle"] from warnings import warn def __getattr__(name): if name in _deprecated_names: warn(f"Importing {name} from IPython.core.display is deprecated since IPython 7.14, please import from IPython display", DeprecationWarning, stacklevel=2) return getattr(display_functions, name) if name in globals().keys(): return globals()[name] else: raise AttributeError(f"module {__name__} has no attribute {name}")
null
176,716
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn import os del os The provided code snippet includes necessary dependencies for implementing the `_safe_exists` function. Write a Python function `def _safe_exists(path)` to solve the following problem: Check path, but don't let exceptions raise Here is the function: def _safe_exists(path): """Check path, but don't let exceptions raise""" try: return os.path.exists(path) except Exception: return False
Check path, but don't let exceptions raise
176,717
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_pretty` function. Write a Python function `def display_pretty(*objs, **kwargs)` to solve the following problem: Display the pretty (default) representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw text 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. Here is the function: def display_pretty(*objs, **kwargs): """Display the pretty (default) representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw text 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('text/plain', objs, **kwargs)
Display the pretty (default) representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw text 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.
176,718
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_html` function. Write a Python function `def display_html(*objs, **kwargs)` to solve the following problem: Display the HTML representation of an object. Note: If raw=False and the object does not have a HTML representation, no HTML will be shown. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw HTML 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. Here is the function: def display_html(*objs, **kwargs): """Display the HTML representation of an object. Note: If raw=False and the object does not have a HTML representation, no HTML will be shown. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw HTML 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('text/html', objs, **kwargs)
Display the HTML representation of an object. Note: If raw=False and the object does not have a HTML representation, no HTML will be shown. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw HTML 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.
176,719
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_markdown` function. Write a Python function `def display_markdown(*objs, **kwargs)` to solve the following problem: Displays the Markdown representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw markdown 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. Here is the function: def display_markdown(*objs, **kwargs): """Displays the Markdown representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw markdown 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('text/markdown', objs, **kwargs)
Displays the Markdown representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw markdown 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.
176,720
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_svg` function. Write a Python function `def display_svg(*objs, **kwargs)` to solve the following problem: Display the SVG representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw svg 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. Here is the function: def display_svg(*objs, **kwargs): """Display the SVG representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw svg 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/svg+xml', objs, **kwargs)
Display the SVG representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw svg 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.
176,721
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_png` function. Write a Python function `def display_png(*objs, **kwargs)` to solve the following problem: Display the PNG representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw png 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. Here is the function: def display_png(*objs, **kwargs): """Display the PNG representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw png 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/png', objs, **kwargs)
Display the PNG representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw png 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.
176,722
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_jpeg` function. Write a Python function `def display_jpeg(*objs, **kwargs)` to solve the following problem: Display the JPEG 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. Here is the function: def display_jpeg(*objs, **kwargs): """Display the JPEG 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/jpeg', objs, **kwargs)
Display the JPEG 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.
176,723
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_latex` function. Write a Python function `def display_latex(*objs, **kwargs)` to solve the following problem: Display the LaTeX representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw latex 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. Here is the function: def display_latex(*objs, **kwargs): """Display the LaTeX representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw latex 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('text/latex', objs, **kwargs)
Display the LaTeX representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw latex 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.
176,724
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_json` function. Write a Python function `def display_json(*objs, **kwargs)` to solve the following problem: Display the JSON representation of an object. Note that not many frontends support displaying JSON. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw json 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. Here is the function: def display_json(*objs, **kwargs): """Display the JSON representation of an object. Note that not many frontends support displaying JSON. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw json 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('application/json', objs, **kwargs)
Display the JSON representation of an object. Note that not many frontends support displaying JSON. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw json 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.
176,725
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_javascript` function. Write a Python function `def display_javascript(*objs, **kwargs)` to solve the following problem: Display the Javascript representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw javascript 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. Here is the function: def display_javascript(*objs, **kwargs): """Display the Javascript representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw javascript 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('application/javascript', objs, **kwargs)
Display the Javascript representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw javascript 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.
176,726
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn def _display_mimetype(mimetype, objs, raw=False, metadata=None): """internal implementation of all display_foo methods Parameters ---------- mimetype : str The mimetype to be published (e.g. 'image/png') *objs : object The Python objects to display, or if raw=True raw text 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. """ if metadata: metadata = {mimetype: metadata} if raw: # turn list of pngdata into list of { 'image/png': pngdata } objs = [ {mimetype: obj} for obj in objs ] display_functions.display(*objs, raw=raw, metadata=metadata, include=[mimetype]) The provided code snippet includes necessary dependencies for implementing the `display_pdf` function. Write a Python function `def display_pdf(*objs, **kwargs)` to solve the following problem: Display the PDF representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw javascript 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. Here is the function: def display_pdf(*objs, **kwargs): """Display the PDF representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw javascript 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('application/pdf', objs, **kwargs)
Display the PDF representation of an object. Parameters ---------- *objs : object The Python objects to display, or if raw=True raw javascript 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.
176,727
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn The provided code snippet includes necessary dependencies for implementing the `_jpegxy` function. Write a Python function `def _jpegxy(data)` to solve the following problem: read the (width, height) from a JPEG header Here is the function: def _jpegxy(data): """read the (width, height) from a JPEG header""" # adapted from http://www.64lines.com/jpeg-width-height idx = 4 while True: block_size = struct.unpack('>H', data[idx:idx+2])[0] idx = idx + block_size if data[idx:idx+2] == b'\xFF\xC0': # found Start of Frame iSOF = idx break else: # read another block idx += 2 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) return w, h
read the (width, height) from a JPEG header
176,728
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn The provided code snippet includes necessary dependencies for implementing the `_gifxy` function. Write a Python function `def _gifxy(data)` to solve the following problem: read the (width, height) from a GIF header Here is the function: def _gifxy(data): """read the (width, height) from a GIF header""" return struct.unpack('<HH', data[6:10])
read the (width, height) from a GIF header
176,729
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn The provided code snippet includes necessary dependencies for implementing the `set_matplotlib_formats` function. Write a Python function `def set_matplotlib_formats(*formats, **kwargs)` to solve the following problem: .. deprecated:: 7.23 use `matplotlib_inline.backend_inline.set_matplotlib_formats()` Select figure formats for the inline backend. Optionally pass quality for JPEG. For example, this enables PNG and JPEG output with a JPEG quality of 90%:: In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) To set this in your config files use the following:: c.InlineBackend.figure_formats = {'png', 'jpeg'} c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) Parameters ---------- *formats : strs One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs Keyword args will be relayed to ``figure.canvas.print_figure``. Here is the function: def set_matplotlib_formats(*formats, **kwargs): """ .. deprecated:: 7.23 use `matplotlib_inline.backend_inline.set_matplotlib_formats()` Select figure formats for the inline backend. Optionally pass quality for JPEG. For example, this enables PNG and JPEG output with a JPEG quality of 90%:: In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) To set this in your config files use the following:: c.InlineBackend.figure_formats = {'png', 'jpeg'} c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) Parameters ---------- *formats : strs One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs Keyword args will be relayed to ``figure.canvas.print_figure``. """ warnings.warn( "`set_matplotlib_formats` is deprecated since IPython 7.23, directly " "use `matplotlib_inline.backend_inline.set_matplotlib_formats()`", DeprecationWarning, stacklevel=2, ) from matplotlib_inline.backend_inline import ( set_matplotlib_formats as set_matplotlib_formats_orig, ) set_matplotlib_formats_orig(*formats, **kwargs)
.. deprecated:: 7.23 use `matplotlib_inline.backend_inline.set_matplotlib_formats()` Select figure formats for the inline backend. Optionally pass quality for JPEG. For example, this enables PNG and JPEG output with a JPEG quality of 90%:: In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) To set this in your config files use the following:: c.InlineBackend.figure_formats = {'png', 'jpeg'} c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) Parameters ---------- *formats : strs One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs Keyword args will be relayed to ``figure.canvas.print_figure``.
176,730
from binascii import b2a_base64, hexlify import html import json import mimetypes import os import struct import warnings from copy import deepcopy from os.path import splitext from pathlib import Path, PurePath from IPython.utils.py3compat import cast_unicode from IPython.testing.skipdoctest import skip_doctest from . import display_functions from warnings import warn The provided code snippet includes necessary dependencies for implementing the `set_matplotlib_close` function. Write a Python function `def set_matplotlib_close(close=True)` to solve the following problem: .. deprecated:: 7.23 use `matplotlib_inline.backend_inline.set_matplotlib_close()` Set whether the inline backend closes all figures automatically or not. By default, the inline backend used in the IPython Notebook will close all matplotlib figures automatically after each cell is run. This means that plots in different cells won't interfere. Sometimes, you may want to make a plot in one cell and then refine it in later cells. This can be accomplished by:: In [1]: set_matplotlib_close(False) To set this in your config files use the following:: c.InlineBackend.close_figures = False Parameters ---------- close : bool Should all matplotlib figures be automatically closed after each cell is run? Here is the function: def set_matplotlib_close(close=True): """ .. deprecated:: 7.23 use `matplotlib_inline.backend_inline.set_matplotlib_close()` Set whether the inline backend closes all figures automatically or not. By default, the inline backend used in the IPython Notebook will close all matplotlib figures automatically after each cell is run. This means that plots in different cells won't interfere. Sometimes, you may want to make a plot in one cell and then refine it in later cells. This can be accomplished by:: In [1]: set_matplotlib_close(False) To set this in your config files use the following:: c.InlineBackend.close_figures = False Parameters ---------- close : bool Should all matplotlib figures be automatically closed after each cell is run? """ warnings.warn( "`set_matplotlib_close` is deprecated since IPython 7.23, directly " "use `matplotlib_inline.backend_inline.set_matplotlib_close()`", DeprecationWarning, stacklevel=2, ) from matplotlib_inline.backend_inline import ( set_matplotlib_close as set_matplotlib_close_orig, ) set_matplotlib_close_orig(close)
.. deprecated:: 7.23 use `matplotlib_inline.backend_inline.set_matplotlib_close()` Set whether the inline backend closes all figures automatically or not. By default, the inline backend used in the IPython Notebook will close all matplotlib figures automatically after each cell is run. This means that plots in different cells won't interfere. Sometimes, you may want to make a plot in one cell and then refine it in later cells. This can be accomplished by:: In [1]: set_matplotlib_close(False) To set this in your config files use the following:: c.InlineBackend.close_figures = False Parameters ---------- close : bool Should all matplotlib figures be automatically closed after each cell is run?
176,731
import os from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme import os del os class TermColors: """Color escape sequences. This class defines the escape sequences for all the standard (ANSI?) colors in terminals. Also defines a NoColor escape which is just the null string, suitable for defining 'dummy' color schemes in terminals which get confused by color escapes. This class should be used as a mixin for building color schemes.""" NoColor = '' # for color schemes in color-less terminals. Normal = '\033[0m' # Reset normal coloring _base = '\033[%sm' # Template for all other colors class ColorScheme: """Generic color scheme class. Just a name and a Struct.""" def __init__(self,__scheme_name_,colordict=None,**colormap): self.name = __scheme_name_ if colordict is None: self.colors = Struct(**colormap) else: self.colors = Struct(colordict) def copy(self,name=None): """Return a full copy of the object, optionally renaming it.""" if name is None: name = self.name return ColorScheme(name, self.colors.dict()) class ColorSchemeTable(dict): """General class to handle tables of color schemes. It's basically a dict of color schemes with a couple of shorthand attributes and some convenient methods. active_scheme_name -> obvious active_colors -> actual color table of the active scheme""" def __init__(self, scheme_list=None, default_scheme=''): """Create a table of color schemes. The table can be created empty and manually filled or it can be created with a list of valid color schemes AND the specification for the default active scheme. """ # create object attributes to be set later self.active_scheme_name = '' self.active_colors = None if scheme_list: if default_scheme == '': raise ValueError('you must specify the default color scheme') for scheme in scheme_list: self.add_scheme(scheme) self.set_active_scheme(default_scheme) def copy(self): """Return full copy of object""" return ColorSchemeTable(self.values(),self.active_scheme_name) def add_scheme(self,new_scheme): """Add a new color scheme to the table.""" if not isinstance(new_scheme,ColorScheme): raise ValueError('ColorSchemeTable only accepts ColorScheme instances') self[new_scheme.name] = new_scheme def set_active_scheme(self,scheme,case_sensitive=0): """Set the currently active scheme. Names are by default compared in a case-insensitive way, but this can be changed by setting the parameter case_sensitive to true.""" scheme_names = list(self.keys()) if case_sensitive: valid_schemes = scheme_names scheme_test = scheme else: valid_schemes = [s.lower() for s in scheme_names] scheme_test = scheme.lower() try: scheme_idx = valid_schemes.index(scheme_test) except ValueError as e: raise ValueError('Unrecognized color scheme: ' + scheme + \ '\nValid schemes: '+str(scheme_names).replace("'', ",'')) from e else: active = scheme_names[scheme_idx] self.active_scheme_name = active self.active_colors = self[active].colors # Now allow using '' as an index for the current active scheme self[''] = self[active] The provided code snippet includes necessary dependencies for implementing the `exception_colors` function. Write a Python function `def exception_colors()` to solve the following problem: Return a color table with fields for exception reporting. The table is an instance of ColorSchemeTable with schemes added for 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled in. Examples: >>> ec = exception_colors() >>> ec.active_scheme_name '' >>> print(ec.active_colors) None Now we activate a color scheme: >>> ec.set_active_scheme('NoColor') >>> ec.active_scheme_name 'NoColor' >>> sorted(ec.active_colors.keys()) ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line', 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName', 'val', 'valEm'] Here is the function: def exception_colors(): """Return a color table with fields for exception reporting. The table is an instance of ColorSchemeTable with schemes added for 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled in. Examples: >>> ec = exception_colors() >>> ec.active_scheme_name '' >>> print(ec.active_colors) None Now we activate a color scheme: >>> ec.set_active_scheme('NoColor') >>> ec.active_scheme_name 'NoColor' >>> sorted(ec.active_colors.keys()) ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line', 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName', 'val', 'valEm'] """ ex_colors = ColorSchemeTable() # Populate it with color schemes C = TermColors # shorthand and local lookup ex_colors.add_scheme(ColorScheme( 'NoColor', # The color to be used for the top line topline = C.NoColor, # The colors to be used in the traceback filename = C.NoColor, lineno = C.NoColor, name = C.NoColor, vName = C.NoColor, val = C.NoColor, em = C.NoColor, # Emphasized colors for the last frame of the traceback normalEm = C.NoColor, filenameEm = C.NoColor, linenoEm = C.NoColor, nameEm = C.NoColor, valEm = C.NoColor, # Colors for printing the exception excName = C.NoColor, line = C.NoColor, caret = C.NoColor, Normal = C.NoColor )) # make some schemes as instances so we can copy them for modification easily ex_colors.add_scheme(ColorScheme( 'Linux', # The color to be used for the top line topline = C.LightRed, # The colors to be used in the traceback filename = C.Green, lineno = C.Green, name = C.Purple, vName = C.Cyan, val = C.Green, em = C.LightCyan, # Emphasized colors for the last frame of the traceback normalEm = C.LightCyan, filenameEm = C.LightGreen, linenoEm = C.LightGreen, nameEm = C.LightPurple, valEm = C.LightBlue, # Colors for printing the exception excName = C.LightRed, line = C.Yellow, caret = C.White, Normal = C.Normal )) # For light backgrounds, swap dark/light colors ex_colors.add_scheme(ColorScheme( 'LightBG', # The color to be used for the top line topline = C.Red, # The colors to be used in the traceback filename = C.LightGreen, lineno = C.LightGreen, name = C.LightPurple, vName = C.Cyan, val = C.LightGreen, em = C.Cyan, # Emphasized colors for the last frame of the traceback normalEm = C.Cyan, filenameEm = C.Green, linenoEm = C.Green, nameEm = C.Purple, valEm = C.Blue, # Colors for printing the exception excName = C.Red, #line = C.Brown, # brown often is displayed as yellow line = C.Red, caret = C.Normal, Normal = C.Normal, )) ex_colors.add_scheme(ColorScheme( 'Neutral', # The color to be used for the top line topline = C.Red, # The colors to be used in the traceback filename = C.LightGreen, lineno = C.LightGreen, name = C.LightPurple, vName = C.Cyan, val = C.LightGreen, em = C.Cyan, # Emphasized colors for the last frame of the traceback normalEm = C.Cyan, filenameEm = C.Green, linenoEm = C.Green, nameEm = C.Purple, valEm = C.Blue, # Colors for printing the exception excName = C.Red, #line = C.Brown, # brown often is displayed as yellow line = C.Red, caret = C.Normal, Normal = C.Normal, )) # Hack: the 'neutral' colours are not very visible on a dark background on # Windows. Since Windows command prompts have a dark background by default, and # relatively few users are likely to alter that, we will use the 'Linux' colours, # designed for a dark background, as the default on Windows. if os.name == "nt": ex_colors.add_scheme(ex_colors['Linux'].copy('Neutral')) return ex_colors
Return a color table with fields for exception reporting. The table is an instance of ColorSchemeTable with schemes added for 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled in. Examples: >>> ec = exception_colors() >>> ec.active_scheme_name '' >>> print(ec.active_colors) None Now we activate a color scheme: >>> ec.set_active_scheme('NoColor') >>> ec.active_scheme_name 'NoColor' >>> sorted(ec.active_colors.keys()) ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line', 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName', 'val', 'valEm']
176,732
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class ProvisionalCompleterWarning(FutureWarning): """ Exception raise by an experimental feature in this module. Wrap code in :any:`provisionalcompleter` context manager if you are certain you want to use an unstable feature. """ pass warnings.filterwarnings('error', category=ProvisionalCompleterWarning) The provided code snippet includes necessary dependencies for implementing the `provisionalcompleter` function. Write a Python function `def provisionalcompleter(action='ignore')` to solve the following problem: This context manager has to be used in any place where unstable completer behavior and API may be called. >>> with provisionalcompleter(): ... completer.do_experimental_things() # works >>> completer.do_experimental_things() # raises. .. note:: Unstable By using this context manager you agree that the API in use may change without warning, and that you won't complain if they do so. You also understand that, if the API is not to your liking, you should report a bug to explain your use case upstream. We'll be happy to get your feedback, feature requests, and improvements on any of the unstable APIs! Here is the function: def provisionalcompleter(action='ignore'): """ This context manager has to be used in any place where unstable completer behavior and API may be called. >>> with provisionalcompleter(): ... completer.do_experimental_things() # works >>> completer.do_experimental_things() # raises. .. note:: Unstable By using this context manager you agree that the API in use may change without warning, and that you won't complain if they do so. You also understand that, if the API is not to your liking, you should report a bug to explain your use case upstream. We'll be happy to get your feedback, feature requests, and improvements on any of the unstable APIs! """ with warnings.catch_warnings(): warnings.filterwarnings(action, category=ProvisionalCompleterWarning) yield
This context manager has to be used in any place where unstable completer behavior and API may be called. >>> with provisionalcompleter(): ... completer.do_experimental_things() # works >>> completer.do_experimental_things() # raises. .. note:: Unstable By using this context manager you agree that the API in use may change without warning, and that you won't complain if they do so. You also understand that, if the API is not to your liking, you should report a bug to explain your use case upstream. We'll be happy to get your feedback, feature requests, and improvements on any of the unstable APIs!
176,733
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ The provided code snippet includes necessary dependencies for implementing the `has_open_quotes` function. Write a Python function `def has_open_quotes(s)` to solve the following problem: Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Returns ------- If there is an open quote, the quote character is returned. Else, return False. Here is the function: def has_open_quotes(s): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Returns ------- If there is an open quote, the quote character is returned. Else, return False. """ # We check " first, then ', so complex cases with nested quotes will get # the " to take precedence. if s.count('"') % 2: return '"' elif s.count("'") % 2: return "'" else: return False
Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Returns ------- If there is an open quote, the quote character is returned. Else, return False.
176,734
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ if sys.platform == 'win32': PROTECTABLES = ' ' else: PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' if sys.platform == 'win32': DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' else: DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False The provided code snippet includes necessary dependencies for implementing the `protect_filename` function. Write a Python function `def protect_filename(s, protectables=PROTECTABLES)` to solve the following problem: Escape a string to protect certain characters. Here is the function: def protect_filename(s, protectables=PROTECTABLES): """Escape a string to protect certain characters.""" if set(s) & set(protectables): if sys.platform == "win32": return '"' + s + '"' else: return "".join(("\\" + c if c in protectables else c) for c in s) else: return s
Escape a string to protect certain characters.
176,735
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ The provided code snippet includes necessary dependencies for implementing the `completions_sorting_key` function. Write a Python function `def completions_sorting_key(word)` to solve the following problem: key for sorting completions This does several things: - Demote any completions starting with underscores to the end - Insert any %magic and %%cellmagic completions in the alphabetical order by their name Here is the function: def completions_sorting_key(word): """key for sorting completions This does several things: - Demote any completions starting with underscores to the end - Insert any %magic and %%cellmagic completions in the alphabetical order by their name """ prio1, prio2 = 0, 0 if word.startswith('__'): prio1 = 2 elif word.startswith('_'): prio1 = 1 if word.endswith('='): prio1 = -1 if word.startswith('%%'): # If there's another % in there, this is something else, so leave it alone if not "%" in word[2:]: word = word[2:] prio2 = 2 elif word.startswith('%'): if not "%" in word[1:]: word = word[1:] prio2 = 1 return prio1, word, prio2
key for sorting completions This does several things: - Demote any completions starting with underscores to the end - Insert any %magic and %%cellmagic completions in the alphabetical order by their name
176,736
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ MatcherAPIv1: TypeAlias = Union[_MatcherAPIv1Base, _MatcherAPIv1Total] Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2] def _get_matcher_api_version(matcher): return getattr(matcher, "matcher_api_version", 1) def _is_matcher_v1(matcher: Matcher) -> TypeGuard[MatcherAPIv1]: api_version = _get_matcher_api_version(matcher) return api_version == 1
null
176,737
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class MatcherAPIv2(Protocol): """Protocol describing Matcher API v2.""" #: API version matcher_api_version: Literal[2] = 2 def __call__(self, context: CompletionContext) -> MatcherResult: """Call signature.""" ... #: Used to construct the default matcher identifier __qualname__: str Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2] def _get_matcher_api_version(matcher): return getattr(matcher, "matcher_api_version", 1) def _is_matcher_v2(matcher: Matcher) -> TypeGuard[MatcherAPIv2]: api_version = _get_matcher_api_version(matcher) return api_version == 2
null
176,738
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ if TYPE_CHECKING or GENERATING_DOCUMENTATION and sys.version_info >= (3, 11): from typing import cast from typing_extensions import TypedDict, NotRequired, Protocol, TypeAlias, TypeGuard else: from typing import Generic def cast(type_, obj): """Workaround for `TypeError: MatcherAPIv2() takes no arguments`""" return obj # do not require on runtime NotRequired = Tuple # requires Python >=3.11 TypedDict = Dict # by extension of `NotRequired` requires 3.11 too Protocol = object # requires Python >=3.8 TypeAlias = Any # requires Python >=3.10 TypeGuard = Generic # requires Python >=3.10 class SimpleCompletion: """Completion item to be included in the dictionary returned by new-style Matcher (API v2). .. warning:: Provisional This class is used to describe the currently supported attributes of simple completion items, and any additional implementation details should not be relied on. Additional attributes may be included in future versions, and meaning of text disambiguated from the current dual meaning of "text to insert" and "text to used as a label". """ __slots__ = ["text", "type"] def __init__(self, text: str, *, type: Optional[str] = None): self.text = text self.type = type def __repr__(self): return f"<SimpleCompletion text={self.text!r} type={self.type!r}>" MatcherResult = Union[SimpleMatcherResult, _JediMatcherResult] def _is_sizable(value: Any) -> TypeGuard[Sized]: """Determines whether objects is sizable""" return hasattr(value, "__len__") def _is_iterator(value: Any) -> TypeGuard[Iterator]: """Determines whether objects is sizable""" return hasattr(value, "__next__") class Iterator(Iterable[_T_co], Protocol[_T_co]): def __next__(self) -> _T_co: ... def __iter__(self) -> Iterator[_T_co]: ... def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `has_any_completions` function. Write a Python function `def has_any_completions(result: MatcherResult) -> bool` to solve the following problem: Check if any result includes any completions. Here is the function: def has_any_completions(result: MatcherResult) -> bool: """Check if any result includes any completions.""" completions = result["completions"] if _is_sizable(completions): return len(completions) != 0 if _is_iterator(completions): try: old_iterator = completions first = next(old_iterator) result["completions"] = cast( Iterator[SimpleCompletion], itertools.chain([first], old_iterator), ) return True except StopIteration: return False raise ValueError( "Completions returned by matcher need to be an Iterator or a Sizable" )
Check if any result includes any completions.
176,739
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ if TYPE_CHECKING or GENERATING_DOCUMENTATION and sys.version_info >= (3, 11): from typing import cast from typing_extensions import TypedDict, NotRequired, Protocol, TypeAlias, TypeGuard else: from typing import Generic def cast(type_, obj): """Workaround for `TypeError: MatcherAPIv2() takes no arguments`""" return obj # do not require on runtime NotRequired = Tuple # requires Python >=3.11 TypedDict = Dict # by extension of `NotRequired` requires 3.11 too Protocol = object # requires Python >=3.8 TypeAlias = Any # requires Python >=3.10 TypeGuard = Generic # requires Python >=3.10 MatcherAPIv1: TypeAlias = Union[_MatcherAPIv1Base, _MatcherAPIv1Total] class MatcherAPIv2(Protocol): """Protocol describing Matcher API v2.""" #: API version matcher_api_version: Literal[2] = 2 def __call__(self, context: CompletionContext) -> MatcherResult: """Call signature.""" ... #: Used to construct the default matcher identifier __qualname__: str Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2] Optional: _SpecialForm = ... TYPE_CHECKING = True def cast(typ: Type[_T], val: Any) -> _T: ... def cast(typ: str, val: Any) -> Any: ... def cast(typ: object, val: Any) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `completion_matcher` function. Write a Python function `def completion_matcher( *, priority: Optional[float] = None, identifier: Optional[str] = None, api_version: int = 1, )` to solve the following problem: Adds attributes describing the matcher. Parameters ---------- priority : Optional[float] The priority of the matcher, determines the order of execution of matchers. Higher priority means that the matcher will be executed first. Defaults to 0. identifier : Optional[str] identifier of the matcher allowing users to modify the behaviour via traitlets, and also used to for debugging (will be passed as ``origin`` with the completions). Defaults to matcher function's ``__qualname__`` (for example, ``IPCompleter.file_matcher`` for the built-in matched defined as a ``file_matcher`` method of the ``IPCompleter`` class). api_version: Optional[int] version of the Matcher API used by this matcher. Currently supported values are 1 and 2. Defaults to 1. Here is the function: def completion_matcher( *, priority: Optional[float] = None, identifier: Optional[str] = None, api_version: int = 1, ): """Adds attributes describing the matcher. Parameters ---------- priority : Optional[float] The priority of the matcher, determines the order of execution of matchers. Higher priority means that the matcher will be executed first. Defaults to 0. identifier : Optional[str] identifier of the matcher allowing users to modify the behaviour via traitlets, and also used to for debugging (will be passed as ``origin`` with the completions). Defaults to matcher function's ``__qualname__`` (for example, ``IPCompleter.file_matcher`` for the built-in matched defined as a ``file_matcher`` method of the ``IPCompleter`` class). api_version: Optional[int] version of the Matcher API used by this matcher. Currently supported values are 1 and 2. Defaults to 1. """ def wrapper(func: Matcher): func.matcher_priority = priority or 0 # type: ignore func.matcher_identifier = identifier or func.__qualname__ # type: ignore func.matcher_api_version = api_version # type: ignore if TYPE_CHECKING: if api_version == 1: func = cast(MatcherAPIv1, func) elif api_version == 2: func = cast(MatcherAPIv2, func) return func return wrapper
Adds attributes describing the matcher. Parameters ---------- priority : Optional[float] The priority of the matcher, determines the order of execution of matchers. Higher priority means that the matcher will be executed first. Defaults to 0. identifier : Optional[str] identifier of the matcher allowing users to modify the behaviour via traitlets, and also used to for debugging (will be passed as ``origin`` with the completions). Defaults to matcher function's ``__qualname__`` (for example, ``IPCompleter.file_matcher`` for the built-in matched defined as a ``file_matcher`` method of the ``IPCompleter`` class). api_version: Optional[int] version of the Matcher API used by this matcher. Currently supported values are 1 and 2. Defaults to 1.
176,740
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2] def _get_matcher_priority(matcher: Matcher): return getattr(matcher, "matcher_priority", 0)
null
176,741
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2] def _get_matcher_id(matcher: Matcher): return getattr(matcher, "matcher_identifier", matcher.__qualname__)
null
176,742
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ _IC = Iterable[Completion] The provided code snippet includes necessary dependencies for implementing the `_deduplicate_completions` function. Write a Python function `def _deduplicate_completions(text: str, completions: _IC)-> _IC` to solve the following problem: Deduplicate a set of completions. .. warning:: Unstable This function is unstable, API may change without warning. Parameters ---------- text : str text that should be completed. completions : Iterator[Completion] iterator over the completions to deduplicate Yields ------ `Completions` objects Completions coming from multiple sources, may be different but end up having the same effect when applied to ``text``. If this is the case, this will consider completions as equal and only emit the first encountered. Not folded in `completions()` yet for debugging purpose, and to detect when the IPython completer does return things that Jedi does not, but should be at some point. Here is the function: def _deduplicate_completions(text: str, completions: _IC)-> _IC: """ Deduplicate a set of completions. .. warning:: Unstable This function is unstable, API may change without warning. Parameters ---------- text : str text that should be completed. completions : Iterator[Completion] iterator over the completions to deduplicate Yields ------ `Completions` objects Completions coming from multiple sources, may be different but end up having the same effect when applied to ``text``. If this is the case, this will consider completions as equal and only emit the first encountered. Not folded in `completions()` yet for debugging purpose, and to detect when the IPython completer does return things that Jedi does not, but should be at some point. """ completions = list(completions) if not completions: return new_start = min(c.start for c in completions) new_end = max(c.end for c in completions) seen = set() for c in completions: new_text = text[new_start:c.start] + c.text + text[c.end:new_end] if new_text not in seen: yield c seen.add(new_text)
Deduplicate a set of completions. .. warning:: Unstable This function is unstable, API may change without warning. Parameters ---------- text : str text that should be completed. completions : Iterator[Completion] iterator over the completions to deduplicate Yields ------ `Completions` objects Completions coming from multiple sources, may be different but end up having the same effect when applied to ``text``. If this is the case, this will consider completions as equal and only emit the first encountered. Not folded in `completions()` yet for debugging purpose, and to detect when the IPython completer does return things that Jedi does not, but should be at some point.
176,743
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class ProvisionalCompleterWarning(FutureWarning): """ Exception raise by an experimental feature in this module. Wrap code in :any:`provisionalcompleter` context manager if you are certain you want to use an unstable feature. """ pass warnings.filterwarnings('error', category=ProvisionalCompleterWarning) class Completion: """ Completion object used and returned by IPython completers. .. warning:: Unstable This function is unstable, API may change without warning. It will also raise unless use in proper context manager. This act as a middle ground :any:`Completion` object between the :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion object. While Jedi need a lot of information about evaluator and how the code should be ran/inspected, PromptToolkit (and other frontend) mostly need user facing information. - Which range should be replaced replaced by what. - Some metadata (like completion type), or meta information to displayed to the use user. For debugging purpose we can also store the origin of the completion (``jedi``, ``IPython.python_matches``, ``IPython.magics_matches``...). """ __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin'] def __init__( self, start: int, end: int, text: str, *, type: Optional[str] = None, _origin="", signature="", ) -> None: warnings.warn( "``Completion`` is a provisional API (as of IPython 6.0). " "It may change without warnings. " "Use in corresponding context manager.", category=ProvisionalCompleterWarning, stacklevel=2, ) self.start = start self.end = end self.text = text self.type = type self.signature = signature self._origin = _origin def __repr__(self): return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \ (self.start, self.end, self.text, self.type or '?', self.signature or '?') def __eq__(self, other) -> bool: """ Equality and hash do not hash the type (as some completer may not be able to infer the type), but are use to (partially) de-duplicate completion. Completely de-duplicating completion is a bit tricker that just comparing as it depends on surrounding text, which Completions are not aware of. """ return self.start == other.start and \ self.end == other.end and \ self.text == other.text def __hash__(self): return hash((self.start, self.end, self.text)) _IC = Iterable[Completion] The provided code snippet includes necessary dependencies for implementing the `rectify_completions` function. Write a Python function `def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC` to solve the following problem: Rectify a set of completions to all have the same ``start`` and ``end`` .. warning:: Unstable This function is unstable, API may change without warning. It will also raise unless use in proper context manager. Parameters ---------- text : str text that should be completed. completions : Iterator[Completion] iterator over the completions to rectify _debug : bool Log failed completion Notes ----- :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though the Jupyter Protocol requires them to behave like so. This will readjust the completion to have the same ``start`` and ``end`` by padding both extremities with surrounding text. During stabilisation should support a ``_debug`` option to log which completion are return by the IPython completer and not found in Jedi in order to make upstream bug report. Here is the function: def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC: """ Rectify a set of completions to all have the same ``start`` and ``end`` .. warning:: Unstable This function is unstable, API may change without warning. It will also raise unless use in proper context manager. Parameters ---------- text : str text that should be completed. completions : Iterator[Completion] iterator over the completions to rectify _debug : bool Log failed completion Notes ----- :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though the Jupyter Protocol requires them to behave like so. This will readjust the completion to have the same ``start`` and ``end`` by padding both extremities with surrounding text. During stabilisation should support a ``_debug`` option to log which completion are return by the IPython completer and not found in Jedi in order to make upstream bug report. """ warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). " "It may change without warnings. " "Use in corresponding context manager.", category=ProvisionalCompleterWarning, stacklevel=2) completions = list(completions) if not completions: return starts = (c.start for c in completions) ends = (c.end for c in completions) new_start = min(starts) new_end = max(ends) seen_jedi = set() seen_python_matches = set() for c in completions: new_text = text[new_start:c.start] + c.text + text[c.end:new_end] if c._origin == 'jedi': seen_jedi.add(new_text) elif c._origin == 'IPCompleter.python_matches': seen_python_matches.add(new_text) yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature) diff = seen_python_matches.difference(seen_jedi) if diff and _debug: print('IPython.python matches have extras:', diff)
Rectify a set of completions to all have the same ``start`` and ``end`` .. warning:: Unstable This function is unstable, API may change without warning. It will also raise unless use in proper context manager. Parameters ---------- text : str text that should be completed. completions : Iterator[Completion] iterator over the completions to rectify _debug : bool Log failed completion Notes ----- :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though the Jupyter Protocol requires them to behave like so. This will readjust the completion to have the same ``start`` and ``end`` by padding both extremities with surrounding text. During stabilisation should support a ``_debug`` option to log which completion are return by the IPython completer and not found in Jedi in order to make upstream bug report.
176,744
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ The provided code snippet includes necessary dependencies for implementing the `get__all__entries` function. Write a Python function `def get__all__entries(obj)` to solve the following problem: returns the strings in the __all__ attribute Here is the function: def get__all__entries(obj): """returns the strings in the __all__ attribute""" try: words = getattr(obj, '__all__') except: return [] return [w for w in words if isinstance(w, str)]
returns the strings in the __all__ attribute
176,745
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class _DictKeyState(enum.Flag): """Represent state of the key match in context of other possible matches. - given `d1 = {'a': 1}` completion on `d1['<tab>` will yield `{'a': END_OF_ITEM}` as there is no tuple. - given `d2 = {('a', 'b'): 1}`: `d2['a', '<tab>` will yield `{'b': END_OF_TUPLE}` as there is no tuple members to add beyond `'b'`. - given `d3 = {('a', 'b'): 1}`: `d3['<tab>` will yield `{'a': IN_TUPLE}` as `'a'` can be added. - given `d4 = {'a': 1, ('a', 'b'): 2}`: `d4['<tab>` will yield `{'a': END_OF_ITEM & END_OF_TUPLE}` """ BASELINE = 0 END_OF_ITEM = enum.auto() END_OF_TUPLE = enum.auto() IN_TUPLE = enum.auto() def _match_number_in_dict_key_prefix(prefix: str) -> Union[str, None]: """Match any valid Python numeric literal in a prefix of dictionary keys. References: - https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals - https://docs.python.org/3/library/tokenize.html """ if prefix[-1].isspace(): # if user typed a space we do not have anything to complete # even if there was a valid number token before return None tokens = _parse_tokens(prefix) rev_tokens = reversed(tokens) skip_over = {tokenize.ENDMARKER, tokenize.NEWLINE} number = None for token in rev_tokens: if token.type in skip_over: continue if number is None: if token.type == tokenize.NUMBER: number = token.string continue else: # we did not match a number return None if token.type == tokenize.OP: if token.string == ",": break if token.string in {"+", "-"}: number = token.string + number else: return None return number _INT_FORMATS = { "0b": bin, "0o": oct, "0x": hex, } def literal_eval(node_or_string: Union[str, AST]) -> Any: ... class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] def __init__(self, **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... def __init__( self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT ) -> None: ... def __missing__(self, key: _KT) -> _VT: ... def copy(self: _S) -> _S: ... Union: _SpecialForm = ... Optional: _SpecialForm = ... List = _Alias() Dict = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `match_dict_keys` function. Write a Python function `def match_dict_keys( keys: List[Union[str, bytes, Tuple[Union[str, bytes], ...]]], prefix: str, delims: str, extra_prefix: Optional[Tuple[Union[str, bytes], ...]] = None, ) -> Tuple[str, int, Dict[str, _DictKeyState]]` to solve the following problem: Used by dict_key_matches, matching the prefix to a list of keys Parameters ---------- keys list of keys in dictionary currently being completed. prefix Part of the text already typed by the user. E.g. `mydict[b'fo` delims String of delimiters to consider when finding the current key. extra_prefix : optional Part of the text already typed in multi-key index cases. E.g. for `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`. Returns ------- A tuple of three elements: ``quote``, ``token_start``, ``matched``, with ``quote`` being the quote that need to be used to close current string. ``token_start`` the position where the replacement should start occurring, ``matches`` a dictionary of replacement/completion keys on keys and values indicating whether the state. Here is the function: def match_dict_keys( keys: List[Union[str, bytes, Tuple[Union[str, bytes], ...]]], prefix: str, delims: str, extra_prefix: Optional[Tuple[Union[str, bytes], ...]] = None, ) -> Tuple[str, int, Dict[str, _DictKeyState]]: """Used by dict_key_matches, matching the prefix to a list of keys Parameters ---------- keys list of keys in dictionary currently being completed. prefix Part of the text already typed by the user. E.g. `mydict[b'fo` delims String of delimiters to consider when finding the current key. extra_prefix : optional Part of the text already typed in multi-key index cases. E.g. for `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`. Returns ------- A tuple of three elements: ``quote``, ``token_start``, ``matched``, with ``quote`` being the quote that need to be used to close current string. ``token_start`` the position where the replacement should start occurring, ``matches`` a dictionary of replacement/completion keys on keys and values indicating whether the state. """ prefix_tuple = extra_prefix if extra_prefix else () prefix_tuple_size = sum( [ # for pandas, do not count slices as taking space not isinstance(k, slice) for k in prefix_tuple ] ) text_serializable_types = (str, bytes, int, float, slice) def filter_prefix_tuple(key): # Reject too short keys if len(key) <= prefix_tuple_size: return False # Reject keys which cannot be serialised to text for k in key: if not isinstance(k, text_serializable_types): return False # Reject keys that do not match the prefix for k, pt in zip(key, prefix_tuple): if k != pt and not isinstance(pt, slice): return False # All checks passed! return True filtered_key_is_final: Dict[ Union[str, bytes, int, float], _DictKeyState ] = defaultdict(lambda: _DictKeyState.BASELINE) for k in keys: # If at least one of the matches is not final, mark as undetermined. # This can happen with `d = {111: 'b', (111, 222): 'a'}` where # `111` appears final on first match but is not final on the second. if isinstance(k, tuple): if filter_prefix_tuple(k): key_fragment = k[prefix_tuple_size] filtered_key_is_final[key_fragment] |= ( _DictKeyState.END_OF_TUPLE if len(k) == prefix_tuple_size + 1 else _DictKeyState.IN_TUPLE ) elif prefix_tuple_size > 0: # we are completing a tuple but this key is not a tuple, # so we should ignore it pass else: if isinstance(k, text_serializable_types): filtered_key_is_final[k] |= _DictKeyState.END_OF_ITEM filtered_keys = filtered_key_is_final.keys() if not prefix: return "", 0, {repr(k): v for k, v in filtered_key_is_final.items()} quote_match = re.search("(?:\"|')", prefix) is_user_prefix_numeric = False if quote_match: quote = quote_match.group() valid_prefix = prefix + quote try: prefix_str = literal_eval(valid_prefix) except Exception: return "", 0, {} else: # If it does not look like a string, let's assume # we are dealing with a number or variable. number_match = _match_number_in_dict_key_prefix(prefix) # We do not want the key matcher to suggest variable names so we yield: if number_match is None: # The alternative would be to assume that user forgort the quote # and if the substring matches, suggest adding it at the start. return "", 0, {} prefix_str = number_match is_user_prefix_numeric = True quote = "" pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' token_match = re.search(pattern, prefix, re.UNICODE) assert token_match is not None # silence mypy token_start = token_match.start() token_prefix = token_match.group() matched: Dict[str, _DictKeyState] = {} str_key: Union[str, bytes] for key in filtered_keys: if isinstance(key, (int, float)): # User typed a number but this key is not a number. if not is_user_prefix_numeric: continue str_key = str(key) if isinstance(key, int): int_base = prefix_str[:2].lower() # if user typed integer using binary/oct/hex notation: if int_base in _INT_FORMATS: int_format = _INT_FORMATS[int_base] str_key = int_format(key) else: # User typed a string but this key is a number. if is_user_prefix_numeric: continue str_key = key try: if not str_key.startswith(prefix_str): continue except (AttributeError, TypeError, UnicodeError) as e: # Python 3+ TypeError on b'a'.startswith('a') or vice-versa continue # reformat remainder of key to begin with prefix rem = str_key[len(prefix_str) :] # force repr wrapped in ' rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') rem_repr = rem_repr[1 + rem_repr.index("'"):-2] if quote == '"': # The entered prefix is quoted with ", # but the match is quoted with '. # A contained " hence needs escaping for comparison: rem_repr = rem_repr.replace('"', '\\"') # then reinsert prefix from start of token match = "%s%s" % (token_prefix, rem_repr) matched[match] = filtered_key_is_final[key] return quote, token_start, matched
Used by dict_key_matches, matching the prefix to a list of keys Parameters ---------- keys list of keys in dictionary currently being completed. prefix Part of the text already typed by the user. E.g. `mydict[b'fo` delims String of delimiters to consider when finding the current key. extra_prefix : optional Part of the text already typed in multi-key index cases. E.g. for `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`. Returns ------- A tuple of three elements: ``quote``, ``token_start``, ``matched``, with ``quote`` being the quote that need to be used to close current string. ``token_start`` the position where the replacement should start occurring, ``matches`` a dictionary of replacement/completion keys on keys and values indicating whether the state.
176,746
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ The provided code snippet includes necessary dependencies for implementing the `cursor_to_position` function. Write a Python function `def cursor_to_position(text:str, line:int, column:int)->int` to solve the following problem: Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Returns ------- Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor : reciprocal of this function Here is the function: def cursor_to_position(text:str, line:int, column:int)->int: """ Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Returns ------- Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor : reciprocal of this function """ lines = text.split('\n') assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) return sum(len(l) + 1 for l in lines[:line]) + column
Convert the (line,column) position of the cursor in text to an offset in a string. Parameters ---------- text : str The text in which to calculate the cursor offset line : int Line of the cursor; 0-indexed column : int Column of the cursor 0-indexed Returns ------- Position of the cursor in ``text``, 0-indexed. See Also -------- position_to_cursor : reciprocal of this function
176,747
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `position_to_cursor` function. Write a Python function `def position_to_cursor(text:str, offset:int)->Tuple[int, int]` to solve the following problem: Convert the position of the cursor in text (0 indexed) to a line number(0-indexed) and a column number (0-indexed) pair Position should be a valid position in ``text``. Parameters ---------- text : str The text in which to calculate the cursor offset offset : int Position of the cursor in ``text``, 0-indexed. Returns ------- (line, column) : (int, int) Line of the cursor; 0-indexed, column of the cursor 0-indexed See Also -------- cursor_to_position : reciprocal of this function Here is the function: def position_to_cursor(text:str, offset:int)->Tuple[int, int]: """ Convert the position of the cursor in text (0 indexed) to a line number(0-indexed) and a column number (0-indexed) pair Position should be a valid position in ``text``. Parameters ---------- text : str The text in which to calculate the cursor offset offset : int Position of the cursor in ``text``, 0-indexed. Returns ------- (line, column) : (int, int) Line of the cursor; 0-indexed, column of the cursor 0-indexed See Also -------- cursor_to_position : reciprocal of this function """ assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text)) before = text[:offset] blines = before.split('\n') # ! splitnes trim trailing \n line = before.count('\n') col = len(blines[-1]) return line, col
Convert the position of the cursor in text (0 indexed) to a line number(0-indexed) and a column number (0-indexed) pair Position should be a valid position in ``text``. Parameters ---------- text : str The text in which to calculate the cursor offset offset : int Position of the cursor in ``text``, 0-indexed. Returns ------- (line, column) : (int, int) Line of the cursor; 0-indexed, column of the cursor 0-indexed See Also -------- cursor_to_position : reciprocal of this function
176,748
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ if sys.platform == 'win32': PROTECTABLES = ' ' else: PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' if sys.platform == 'win32': DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' else: DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False The provided code snippet includes necessary dependencies for implementing the `_safe_isinstance` function. Write a Python function `def _safe_isinstance(obj, module, class_name, *attrs)` to solve the following problem: Checks if obj is an instance of module.class_name if loaded Here is the function: def _safe_isinstance(obj, module, class_name, *attrs): """Checks if obj is an instance of module.class_name if loaded """ if module in sys.modules: m = sys.modules[module] for attr in [class_name, *attrs]: m = getattr(m, attr) return isinstance(obj, m)
Checks if obj is an instance of module.class_name if loaded
176,749
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class CompletionContext: """Completion context provided as an argument to matchers in the Matcher API v2.""" # rationale: many legacy matchers relied on completer state (`self.text_until_cursor`) # which was not explicitly visible as an argument of the matcher, making any refactor # prone to errors; by explicitly passing `cursor_position` we can decouple the matchers # from the completer, and make substituting them in sub-classes easier. #: Relevant fragment of code directly preceding the cursor. #: The extraction of token is implemented via splitter heuristic #: (following readline behaviour for legacy reasons), which is user configurable #: (by switching the greedy mode). token: str #: The full available content of the editor or buffer full_text: str #: Cursor position in the line (the same for ``full_text`` and ``text``). cursor_position: int #: Cursor line in ``full_text``. cursor_line: int #: The maximum number of completions that will be used downstream. #: Matchers can use this information to abort early. #: The built-in Jedi matcher is currently excepted from this limit. # If not given, return all possible completions. limit: Optional[int] def text_until_cursor(self) -> str: return self.line_with_cursor[: self.cursor_position] def line_with_cursor(self) -> str: return self.full_text.split("\n")[self.cursor_line] def back_unicode_name_matches(text: str) -> Tuple[str, Sequence[str]]: """Match Unicode characters back to Unicode name This does ``☃`` -> ``\\snowman`` Note that snowman is not a valid python3 combining character but will be expanded. Though it will not recombine back to the snowman character by the completion machinery. This will not either back-complete standard sequences like \\n, \\b ... .. deprecated:: 8.6 You can use :meth:`back_unicode_name_matcher` instead. Returns ======= Return a tuple with two elements: - The Unicode character that was matched (preceded with a backslash), or empty string, - a sequence (of 1), name for the match Unicode character, preceded by backslash, or empty if no match. """ if len(text)<2: return '', () maybe_slash = text[-2] if maybe_slash != '\\': return '', () char = text[-1] # no expand on quote for completion in strings. # nor backcomplete standard ascii keys if char in string.ascii_letters or char in ('"',"'"): return '', () try : unic = unicodedata.name(char) return '\\'+char,('\\'+unic,) except KeyError: pass return '', () def _convert_matcher_v1_result_to_v2( matches: Sequence[str], type: str, fragment: Optional[str] = None, suppress_if_matches: bool = False, ) -> SimpleMatcherResult: """Utility to help with transition""" result = { "completions": [SimpleCompletion(text=match, type=type) for match in matches], "suppress": (True if matches else False) if suppress_if_matches else False, } if fragment is not None: result["matched_fragment"] = fragment return cast(SimpleMatcherResult, result) The provided code snippet includes necessary dependencies for implementing the `back_unicode_name_matcher` function. Write a Python function `def back_unicode_name_matcher(context: CompletionContext)` to solve the following problem: Match Unicode characters back to Unicode name Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API. Here is the function: def back_unicode_name_matcher(context: CompletionContext): """Match Unicode characters back to Unicode name Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API. """ fragment, matches = back_unicode_name_matches(context.text_until_cursor) return _convert_matcher_v1_result_to_v2( matches, type="unicode", fragment=fragment, suppress_if_matches=True )
Match Unicode characters back to Unicode name Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API.
176,750
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ class CompletionContext: """Completion context provided as an argument to matchers in the Matcher API v2.""" # rationale: many legacy matchers relied on completer state (`self.text_until_cursor`) # which was not explicitly visible as an argument of the matcher, making any refactor # prone to errors; by explicitly passing `cursor_position` we can decouple the matchers # from the completer, and make substituting them in sub-classes easier. #: Relevant fragment of code directly preceding the cursor. #: The extraction of token is implemented via splitter heuristic #: (following readline behaviour for legacy reasons), which is user configurable #: (by switching the greedy mode). token: str #: The full available content of the editor or buffer full_text: str #: Cursor position in the line (the same for ``full_text`` and ``text``). cursor_position: int #: Cursor line in ``full_text``. cursor_line: int #: The maximum number of completions that will be used downstream. #: Matchers can use this information to abort early. #: The built-in Jedi matcher is currently excepted from this limit. # If not given, return all possible completions. limit: Optional[int] def text_until_cursor(self) -> str: return self.line_with_cursor[: self.cursor_position] def line_with_cursor(self) -> str: return self.full_text.split("\n")[self.cursor_line] def back_latex_name_matches(text: str) -> Tuple[str, Sequence[str]]: """Match latex characters back to unicode name This does ``\\ℵ`` -> ``\\aleph`` .. deprecated:: 8.6 You can use :meth:`back_latex_name_matcher` instead. """ if len(text)<2: return '', () maybe_slash = text[-2] if maybe_slash != '\\': return '', () char = text[-1] # no expand on quote for completion in strings. # nor backcomplete standard ascii keys if char in string.ascii_letters or char in ('"',"'"): return '', () try : latex = reverse_latex_symbol[char] # '\\' replace the \ as well return '\\'+char,[latex] except KeyError: pass return '', () def _convert_matcher_v1_result_to_v2( matches: Sequence[str], type: str, fragment: Optional[str] = None, suppress_if_matches: bool = False, ) -> SimpleMatcherResult: """Utility to help with transition""" result = { "completions": [SimpleCompletion(text=match, type=type) for match in matches], "suppress": (True if matches else False) if suppress_if_matches else False, } if fragment is not None: result["matched_fragment"] = fragment return cast(SimpleMatcherResult, result) The provided code snippet includes necessary dependencies for implementing the `back_latex_name_matcher` function. Write a Python function `def back_latex_name_matcher(context: CompletionContext)` to solve the following problem: Match latex characters back to unicode name Same as :any:`back_latex_name_matches`, but adopted to new Matcher API. Here is the function: def back_latex_name_matcher(context: CompletionContext): """Match latex characters back to unicode name Same as :any:`back_latex_name_matches`, but adopted to new Matcher API. """ fragment, matches = back_latex_name_matches(context.text_until_cursor) return _convert_matcher_v1_result_to_v2( matches, type="latex", fragment=fragment, suppress_if_matches=True )
Match latex characters back to unicode name Same as :any:`back_latex_name_matches`, but adopted to new Matcher API.
176,751
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ def _formatparamchildren(parameter) -> str: """ Get parameter name and value from Jedi Private API Jedi does not expose a simple way to get `param=value` from its API. Parameters ---------- parameter Jedi's function `Param` Returns ------- A string like 'a', 'b=1', '*args', '**kwargs' """ description = parameter.description if not description.startswith('param '): raise ValueError('Jedi function parameter description have change format.' 'Expected "param ...", found %r".' % description) return description[6:] The provided code snippet includes necessary dependencies for implementing the `_make_signature` function. Write a Python function `def _make_signature(completion)-> str` to solve the following problem: Make the signature from a jedi completion Parameters ---------- completion : jedi.Completion object does not complete a function type Returns ------- a string consisting of the function signature, with the parenthesis but without the function name. example: `(a, *args, b=1, **kwargs)` Here is the function: def _make_signature(completion)-> str: """ Make the signature from a jedi completion Parameters ---------- completion : jedi.Completion object does not complete a function type Returns ------- a string consisting of the function signature, with the parenthesis but without the function name. example: `(a, *args, b=1, **kwargs)` """ # it looks like this might work on jedi 0.17 if hasattr(completion, 'get_signatures'): signatures = completion.get_signatures() if not signatures: return '(?)' c0 = completion.get_signatures()[0] return '('+c0.to_string().split('(', maxsplit=1)[1] return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures() for p in signature.defined_names()) if f])
Make the signature from a jedi completion Parameters ---------- completion : jedi.Completion object does not complete a function type Returns ------- a string consisting of the function signature, with the parenthesis but without the function name. example: `(a, *args, b=1, **kwargs)`
176,752
from __future__ import annotations import builtins as builtin_mod import enum import glob import inspect import itertools import keyword import os import re import string import sys import tokenize import time import unicodedata import uuid import warnings from ast import literal_eval from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from functools import cached_property, partial from types import SimpleNamespace from typing import ( Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, Optional, TYPE_CHECKING, Set, Sized, TypeVar, Literal, ) from IPython.core.guarded_eval import guarded_eval, EvaluationContext from IPython.core.error import TryNext from IPython.core.inputtransformer2 import ESC_MAGIC from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol from IPython.core.oinspect import InspectColors from IPython.testing.skipdoctest import skip_doctest from IPython.utils import generics from IPython.utils.decorators import sphinx_options from IPython.utils.dir2 import dir2, get_real_method from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.path import ensure_dir_exists from IPython.utils.process import arg_split from traitlets import ( Bool, Enum, Int, List as ListTrait, Unicode, Dict as DictTrait, Union as UnionTrait, observe, ) from traitlets.config.configurable import Configurable import __main__ List = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]: names = [] for start,stop in ranges: for c in range(start, stop) : try: names.append(unicodedata.name(chr(c))) except ValueError: pass return names
null
176,753
import abc import sys import traceback import warnings from io import StringIO from decorator import decorator from traitlets.config.configurable import Configurable from .getipython import get_ipython from ..utils.sentinel import Sentinel from ..utils.dir2 import get_real_method from ..lib import pretty from traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, default, observe, ) from typing import Any The provided code snippet includes necessary dependencies for implementing the `_safe_repr` function. Write a Python function `def _safe_repr(obj)` to solve the following problem: Try to return a repr of an object always returns a string, at least. Here is the function: def _safe_repr(obj): """Try to return a repr of an object always returns a string, at least. """ try: return repr(obj) except Exception as e: return "un-repr-able object (%r)" % e
Try to return a repr of an object always returns a string, at least.
176,754
import abc import sys import traceback import warnings from io import StringIO from decorator import decorator from traitlets.config.configurable import Configurable from .getipython import get_ipython from ..utils.sentinel import Sentinel from ..utils.dir2 import get_real_method from ..lib import pretty from traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, default, observe, ) from typing import Any import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False def get_ipython(): """Get the global InteractiveShell instance. Returns None if no InteractiveShell instance is registered. """ from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): return InteractiveShell.instance() The provided code snippet includes necessary dependencies for implementing the `catch_format_error` function. Write a Python function `def catch_format_error(method, self, *args, **kwargs)` to solve the following problem: show traceback on failed format call Here is the function: def catch_format_error(method, self, *args, **kwargs): """show traceback on failed format call""" try: r = method(self, *args, **kwargs) except NotImplementedError: # don't warn on NotImplementedErrors return self._check_return(None, args[0]) except Exception: exc_info = sys.exc_info() ip = get_ipython() if ip is not None: ip.showtraceback(exc_info) else: traceback.print_exception(*exc_info) return self._check_return(None, args[0]) return self._check_return(r, args[0])
show traceback on failed format call
176,755
import abc import sys import traceback import warnings from io import StringIO from decorator import decorator from traitlets.config.configurable import Configurable from .getipython import get_ipython from ..utils.sentinel import Sentinel from ..utils.dir2 import get_real_method from ..lib import pretty from traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, default, observe, ) from typing import Any The provided code snippet includes necessary dependencies for implementing the `_mod_name_key` function. Write a Python function `def _mod_name_key(typ)` to solve the following problem: Return a (__module__, __name__) tuple for a type. Used as key in Formatter.deferred_printers. Here is the function: def _mod_name_key(typ): """Return a (__module__, __name__) tuple for a type. Used as key in Formatter.deferred_printers. """ module = getattr(typ, '__module__', None) name = getattr(typ, '__name__', None) return (module, name)
Return a (__module__, __name__) tuple for a type. Used as key in Formatter.deferred_printers.
176,756
import abc import sys import traceback import warnings from io import StringIO from decorator import decorator from traitlets.config.configurable import Configurable from .getipython import get_ipython from ..utils.sentinel import Sentinel from ..utils.dir2 import get_real_method from ..lib import pretty from traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, default, observe, ) from typing import Any The provided code snippet includes necessary dependencies for implementing the `_get_type` function. Write a Python function `def _get_type(obj)` to solve the following problem: Return the type of an instance (old and new-style) Here is the function: def _get_type(obj): """Return the type of an instance (old and new-style)""" return getattr(obj, '__class__', None) or type(obj)
Return the type of an instance (old and new-style)
176,757
import abc import sys import traceback import warnings from io import StringIO from decorator import decorator from traitlets.config.configurable import Configurable from .getipython import get_ipython from ..utils.sentinel import Sentinel from ..utils.dir2 import get_real_method from ..lib import pretty from traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, default, observe, ) from typing import Any class InteractiveShell(SingletonConfigurable): """An enhanced, interactive shell for Python.""" _instance = None ast_transformers = List([], help= """ A list of ast.NodeTransformer subclass instances, which will be applied to user input before code is run. """ ).tag(config=True) autocall = Enum((0,1,2), default_value=0, help= """ Make IPython automatically call any callable object even if you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. The value can be '0' to disable the feature, '1' for 'smart' autocall, where it is not applied if there are no more arguments on the line, and '2' for 'full' autocall, where all callable objects are automatically called (even if no arguments are present). """ ).tag(config=True) autoindent = Bool(True, help= """ Autoindent IPython code entered interactively. """ ).tag(config=True) autoawait = Bool(True, help= """ Automatically run await statement in the top level repl. """ ).tag(config=True) loop_runner_map ={ 'asyncio':(_asyncio_runner, True), 'curio':(_curio_runner, True), 'trio':(_trio_runner, True), 'sync': (_pseudo_sync_runner, False) } loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner", allow_none=True, help="""Select the loop runner that will be used to execute top-level asynchronous code""" ).tag(config=True) def _default_loop_runner(self): return import_item("IPython.core.interactiveshell._asyncio_runner") def _import_runner(self, proposal): if isinstance(proposal.value, str): if proposal.value in self.loop_runner_map: runner, autoawait = self.loop_runner_map[proposal.value] self.autoawait = autoawait return runner runner = import_item(proposal.value) if not callable(runner): raise ValueError('loop_runner must be callable') return runner if not callable(proposal.value): raise ValueError('loop_runner must be callable') return proposal.value automagic = Bool(True, help= """ Enable magic commands to be called without the leading %. """ ).tag(config=True) banner1 = Unicode(default_banner, help="""The part of the banner to be printed before the profile""" ).tag(config=True) banner2 = Unicode('', help="""The part of the banner to be printed after the profile""" ).tag(config=True) cache_size = Integer(1000, help= """ Set the size of the output cache. The default is 1000, you can change it permanently in your config file. Setting it to 0 completely disables the caching system, and the minimum value accepted is 3 (if you provide a value less than 3, it is reset to 0 and a warning is issued). This limit is defined because otherwise you'll spend more time re-flushing a too small cache than working """ ).tag(config=True) color_info = Bool(True, help= """ Use colors for displaying information about objects. Because this information is passed through a pager (like 'less'), and some pagers get confused with color codes, this capability can be turned off. """ ).tag(config=True) colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), default_value='Neutral', help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." ).tag(config=True) debug = Bool(False).tag(config=True) disable_failing_post_execute = Bool(False, help="Don't call post-execute functions that have failed in the past." ).tag(config=True) display_formatter = Instance(DisplayFormatter, allow_none=True) displayhook_class = Type(DisplayHook) display_pub_class = Type(DisplayPublisher) compiler_class = Type(CachingCompiler) inspector_class = Type( oinspect.Inspector, help="Class to use to instantiate the shell inspector" ).tag(config=True) sphinxify_docstring = Bool(False, help= """ Enables rich html representation of docstrings. (This requires the docrepr module). """).tag(config=True) def _sphinxify_docstring_changed(self, change): if change['new']: warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) enable_html_pager = Bool(False, help= """ (Provisional API) enables html representation in mime bundles sent to pagers. """).tag(config=True) def _enable_html_pager_changed(self, change): if change['new']: warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) data_pub_class = None exit_now = Bool(False) exiter = Instance(ExitAutocall) def _exiter_default(self): return ExitAutocall(self) # Monotonically increasing execution counter execution_count = Integer(1) filename = Unicode("<ipython console>") ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ # Used to transform cells before running them, and check whether code is complete input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', ()) def input_transformers_cleanup(self): return self.input_transformer_manager.cleanup_transforms input_transformers_post = List([], help="A list of string input transformers, to be applied after IPython's " "own input transformations." ) def input_splitter(self): """Make this available for backward compatibility (pre-7.0 release) with existing code. For example, ipykernel ipykernel currently uses `shell.input_splitter.check_complete` """ from warnings import warn warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.", DeprecationWarning, stacklevel=2 ) return self.input_transformer_manager logstart = Bool(False, help= """ Start logging to the default log file in overwrite mode. Use `logappend` to specify a log file to **append** logs to. """ ).tag(config=True) logfile = Unicode('', help= """ The name of the logfile to use. """ ).tag(config=True) logappend = Unicode('', help= """ Start logging to the given file in append mode. Use `logfile` to specify a log file to **overwrite** logs to. """ ).tag(config=True) object_info_string_level = Enum((0,1,2), default_value=0, ).tag(config=True) pdb = Bool(False, help= """ Automatically call the pdb debugger after every exception. """ ).tag(config=True) display_page = Bool(False, help="""If True, anything that would be passed to the pager will be displayed as regular output instead.""" ).tag(config=True) show_rewritten_input = Bool(True, help="Show rewritten input, e.g. for autocall." ).tag(config=True) quiet = Bool(False).tag(config=True) history_length = Integer(10000, help='Total length of command history' ).tag(config=True) history_load_length = Integer(1000, help= """ The number of saved history entries to be loaded into the history buffer at startup. """ ).tag(config=True) ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], default_value='last_expr', help=""" 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying which nodes should be run interactively (displaying output from expressions). """ ).tag(config=True) warn_venv = Bool( True, help="Warn if running in a virtual environment with no IPython installed (so IPython from the global environment is used).", ).tag(config=True) # TODO: this part of prompt management should be moved to the frontends. # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' separate_in = SeparateUnicode('\n').tag(config=True) separate_out = SeparateUnicode('').tag(config=True) separate_out2 = SeparateUnicode('').tag(config=True) wildcards_case_sensitive = Bool(True).tag(config=True) xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'), default_value='Context', help="Switch modes for the IPython exception handlers." ).tag(config=True) # Subcomponents of InteractiveShell alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) def profile(self): if self.profile_dir is not None: name = os.path.basename(self.profile_dir.location) return name.replace('profile_','') # Private interface _post_execute = Dict() # Tracks any GUI loop loaded for pylab pylab_gui_select = None last_execution_succeeded = Bool(True, help='Did last executed command succeeded') last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) def __init__(self, ipython_dir=None, profile_dir=None, user_module=None, user_ns=None, custom_exceptions=((), None), **kwargs): # This is where traits with a config_key argument are updated # from the values on config. super(InteractiveShell, self).__init__(**kwargs) if 'PromptManager' in self.config: warn('As of IPython 5.0 `PromptManager` config will have no effect' ' and has been replaced by TerminalInteractiveShell.prompts_class') self.configurables = [self] # These are relatively independent and stateless self.init_ipython_dir(ipython_dir) self.init_profile_dir(profile_dir) self.init_instance_attrs() self.init_environment() # Check if we're in a virtualenv, and set up sys.path. self.init_virtualenv() # Create namespaces (user_ns, user_global_ns, etc.) self.init_create_namespaces(user_module, user_ns) # This has to be done after init_create_namespaces because it uses # something in self.user_ns, but before init_sys_modules, which # is the first thing to modify sys. # TODO: When we override sys.stdout and sys.stderr before this class # is created, we are saving the overridden ones here. Not sure if this # is what we want to do. self.save_sys_module_state() self.init_sys_modules() # While we're trying to have each part of the code directly access what # it needs without keeping redundant references to objects, we have too # much legacy code that expects ip.db to exist. self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) self.init_history() self.init_encoding() self.init_prefilter() self.init_syntax_highlighting() self.init_hooks() self.init_events() self.init_pushd_popd_magic() self.init_user_ns() self.init_logger() self.init_builtins() # The following was in post_config_initialization self.init_inspector() self.raw_input_original = input self.init_completer() # TODO: init_io() needs to happen before init_traceback handlers # because the traceback handlers hardcode the stdout/stderr streams. # This logic in in debugger.Pdb and should eventually be changed. self.init_io() self.init_traceback_handlers(custom_exceptions) self.init_prompts() self.init_display_formatter() self.init_display_pub() self.init_data_pub() self.init_displayhook() self.init_magics() self.init_alias() self.init_logstart() self.init_pdb() self.init_extension_manager() self.init_payload() self.events.trigger('shell_initialized', self) atexit.register(self.atexit_operations) # The trio runner is used for running Trio in the foreground thread. It # is different from `_trio_runner(async_fn)` in `async_helpers.py` # which calls `trio.run()` for every cell. This runner runs all cells # inside a single Trio event loop. If used, it is set from # `ipykernel.kernelapp`. self.trio_runner = None def get_ipython(self): """Return the currently running IPython instance.""" return self #------------------------------------------------------------------------- # Trait changed handlers #------------------------------------------------------------------------- def _ipython_dir_changed(self, change): ensure_dir_exists(change['new']) def set_autoindent(self,value=None): """Set the autoindent flag. If called with no arguments, it acts as a toggle.""" if value is None: self.autoindent = not self.autoindent else: self.autoindent = value def set_trio_runner(self, tr): self.trio_runner = tr #------------------------------------------------------------------------- # init_* methods called by __init__ #------------------------------------------------------------------------- def init_ipython_dir(self, ipython_dir): if ipython_dir is not None: self.ipython_dir = ipython_dir return self.ipython_dir = get_ipython_dir() def init_profile_dir(self, profile_dir): if profile_dir is not None: self.profile_dir = profile_dir return self.profile_dir = ProfileDir.create_profile_dir_by_name( self.ipython_dir, "default" ) def init_instance_attrs(self): self.more = False # command compiler self.compile = self.compiler_class() # Make an empty namespace, which extension writers can rely on both # existing and NEVER being used by ipython itself. This gives them a # convenient location for storing additional information and state # their extensions may require, without fear of collisions with other # ipython names that may develop later. self.meta = Struct() # Temporary files used for various purposes. Deleted at exit. # The files here are stored with Path from Pathlib self.tempfiles = [] self.tempdirs = [] # keep track of where we started running (mainly for crash post-mortem) # This is not being used anywhere currently. self.starting_dir = os.getcwd() # Indentation management self.indent_current_nsp = 0 # Dict to track post-execution functions that have been registered self._post_execute = {} def init_environment(self): """Any changes we need to make to the user's environment.""" pass def init_encoding(self): # Get system encoding at startup time. Certain terminals (like Emacs # under Win32 have it set to None, and we need to have a known valid # encoding to use in the raw_input() method try: self.stdin_encoding = sys.stdin.encoding or 'ascii' except AttributeError: self.stdin_encoding = 'ascii' def init_syntax_highlighting(self, changes=None): # Python source parser/formatter for syntax highlighting pyformat = PyColorize.Parser(style=self.colors, parent=self).format self.pycolorize = lambda src: pyformat(src,'str') def refresh_style(self): # No-op here, used in subclass pass def init_pushd_popd_magic(self): # for pushd/popd management self.home_dir = get_home_dir() self.dir_stack = [] def init_logger(self): self.logger = Logger(self.home_dir, logfname='ipython_log.py', logmode='rotate') def init_logstart(self): """Initialize logging in case it was requested at the command line. """ if self.logappend: self.magic('logstart %s append' % self.logappend) elif self.logfile: self.magic('logstart %s' % self.logfile) elif self.logstart: self.magic('logstart') def init_builtins(self): # A single, static flag that we set to True. Its presence indicates # that an IPython shell has been created, and we make no attempts at # removing on exit or representing the existence of more than one # IPython at a time. builtin_mod.__dict__['__IPYTHON__'] = True builtin_mod.__dict__['display'] = display self.builtin_trap = BuiltinTrap(shell=self) def init_inspector(self, changes=None): # Object inspector self.inspector = self.inspector_class( oinspect.InspectColors, PyColorize.ANSICodeColors, self.colors, self.object_info_string_level, ) def init_io(self): # implemented in subclasses, TerminalInteractiveShell does call # colorama.init(). pass def init_prompts(self): # Set system prompts, so that scripts can decide if they are running # interactively. sys.ps1 = 'In : ' sys.ps2 = '...: ' sys.ps3 = 'Out: ' def init_display_formatter(self): self.display_formatter = DisplayFormatter(parent=self) self.configurables.append(self.display_formatter) def init_display_pub(self): self.display_pub = self.display_pub_class(parent=self, shell=self) self.configurables.append(self.display_pub) def init_data_pub(self): if not self.data_pub_class: self.data_pub = None return self.data_pub = self.data_pub_class(parent=self) self.configurables.append(self.data_pub) def init_displayhook(self): # Initialize displayhook, set in/out prompts and printing system self.displayhook = self.displayhook_class( parent=self, shell=self, cache_size=self.cache_size, ) self.configurables.append(self.displayhook) # This is a context manager that installs/revmoes the displayhook at # the appropriate time. self.display_trap = DisplayTrap(hook=self.displayhook) def get_path_links(p: Path): """Gets path links including all symlinks Examples -------- In [1]: from IPython.core.interactiveshell import InteractiveShell In [2]: import sys, pathlib In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable)) In [4]: len(paths) == len(set(paths)) Out[4]: True In [5]: bool(paths) Out[5]: True """ paths = [p] while p.is_symlink(): new_path = Path(os.readlink(p)) if not new_path.is_absolute(): new_path = p.parent / new_path p = new_path paths.append(p) return paths def init_virtualenv(self): """Add the current virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. Adapted from code snippets online. http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv """ if 'VIRTUAL_ENV' not in os.environ: # Not in a virtualenv return elif os.environ["VIRTUAL_ENV"] == "": warn("Virtual env path set to '', please check if this is intended.") return p = Path(sys.executable) p_venv = Path(os.environ["VIRTUAL_ENV"]) # fallback venv detection: # stdlib venv may symlink sys.executable, so we can't use realpath. # but others can symlink *to* the venv Python, so we can't just use sys.executable. # So we just check every item in the symlink tree (generally <= 3) paths = self.get_path_links(p) # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible if p_venv.parts[1] == "cygdrive": drive_name = p_venv.parts[2] p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:]) if any(p_venv == p.parents[1] for p in paths): # Our exe is inside or has access to the virtualenv, don't need to do anything. return if sys.platform == "win32": virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages")) else: virtual_env_path = Path( os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages" ) p_ver = sys.version_info[:2] # Predict version from py[thon]-x.x in the $VIRTUAL_ENV re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"]) if re_m: predicted_path = Path(str(virtual_env_path).format(*re_m.groups())) if predicted_path.exists(): p_ver = re_m.groups() virtual_env = str(virtual_env_path).format(*p_ver) if self.warn_venv: warn( "Attempting to work in a virtualenv. If you encounter problems, " "please install IPython inside the virtualenv." ) import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env) #------------------------------------------------------------------------- # Things related to injections into the sys module #------------------------------------------------------------------------- def save_sys_module_state(self): """Save the state of hooks in the sys module. This has to be called after self.user_module is created. """ self._orig_sys_module_state = {'stdin': sys.stdin, 'stdout': sys.stdout, 'stderr': sys.stderr, 'excepthook': sys.excepthook} self._orig_sys_modules_main_name = self.user_module.__name__ self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) def restore_sys_module_state(self): """Restore the state of the sys module.""" try: for k, v in self._orig_sys_module_state.items(): setattr(sys, k, v) except AttributeError: pass # Reset what what done in self.init_sys_modules if self._orig_sys_modules_main_mod is not None: sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod #------------------------------------------------------------------------- # Things related to the banner #------------------------------------------------------------------------- def banner(self): banner = self.banner1 if self.profile and self.profile != 'default': banner += '\nIPython profile: %s\n' % self.profile if self.banner2: banner += '\n' + self.banner2 return banner def show_banner(self, banner=None): if banner is None: banner = self.banner sys.stdout.write(banner) #------------------------------------------------------------------------- # Things related to hooks #------------------------------------------------------------------------- def init_hooks(self): # hooks holds pointers used for user-side customizations self.hooks = Struct() self.strdispatchers = {} # Set all default hooks, defined in the IPython.hooks module. hooks = IPython.core.hooks for hook_name in hooks.__all__: # default hooks have priority 100, i.e. low; user hooks should have # 0-100 priority self.set_hook(hook_name, getattr(hooks, hook_name), 100) if self.display_page: self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) def set_hook(self, name, hook, priority=50, str_key=None, re_key=None): """set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to call at runtime your own routines.""" # At some point in the future, this should validate the hook before it # accepts it. Probably at least check that the hook takes the number # of args it's supposed to. f = types.MethodType(hook,self) # check if the hook is for strdispatcher first if str_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_s(str_key, f, priority ) self.strdispatchers[name] = sdp return if re_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_re(re.compile(re_key), f, priority ) self.strdispatchers[name] = sdp return dp = getattr(self.hooks, name, None) if name not in IPython.core.hooks.__all__: print("Warning! Hook '%s' is not one of %s" % \ (name, IPython.core.hooks.__all__ )) if name in IPython.core.hooks.deprecated: alternative = IPython.core.hooks.deprecated[name] raise ValueError( "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format( name, alternative ) ) if not dp: dp = IPython.core.hooks.CommandChainDispatcher() try: dp.add(f,priority) except AttributeError: # it was not commandchain, plain old func - replace dp = f setattr(self.hooks,name, dp) #------------------------------------------------------------------------- # Things related to events #------------------------------------------------------------------------- def init_events(self): self.events = EventManager(self, available_events) self.events.register("pre_execute", self._clear_warning_registry) def register_post_execute(self, func): """DEPRECATED: Use ip.events.register('post_run_cell', func) Register a function for calling after code execution. """ raise ValueError( "ip.register_post_execute is deprecated since IPython 1.0, use " "ip.events.register('post_run_cell', func) instead." ) def _clear_warning_registry(self): # clear the warning registry, so that different code blocks with # overlapping line number ranges don't cause spurious suppression of # warnings (see gh-6611 for details) if "__warningregistry__" in self.user_global_ns: del self.user_global_ns["__warningregistry__"] #------------------------------------------------------------------------- # Things related to the "main" module #------------------------------------------------------------------------- def new_main_mod(self, filename, modname): """Return a new 'main' module object for user code execution. ``filename`` should be the path of the script which will be run in the module. Requests with the same filename will get the same module, with its namespace cleared. ``modname`` should be the module name - normally either '__main__' or the basename of the file without the extension. When scripts are executed via %run, we must keep a reference to their __main__ module around so that Python doesn't clear it, rendering references to module globals useless. This method keeps said reference in a private dict, keyed by the absolute path of the script. This way, for multiple executions of the same script we only keep one copy of the namespace (the last one), thus preventing memory leaks from old references while allowing the objects from the last execution to be accessible. """ filename = os.path.abspath(filename) try: main_mod = self._main_mod_cache[filename] except KeyError: main_mod = self._main_mod_cache[filename] = types.ModuleType( modname, doc="Module created for script run in IPython") else: main_mod.__dict__.clear() main_mod.__name__ = modname main_mod.__file__ = filename # It seems pydoc (and perhaps others) needs any module instance to # implement a __nonzero__ method main_mod.__nonzero__ = lambda : True return main_mod def clear_main_mod_cache(self): """Clear the cache of main modules. Mainly for use by utilities like %reset. Examples -------- In [15]: import IPython In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') In [17]: len(_ip._main_mod_cache) > 0 Out[17]: True In [18]: _ip.clear_main_mod_cache() In [19]: len(_ip._main_mod_cache) == 0 Out[19]: True """ self._main_mod_cache.clear() #------------------------------------------------------------------------- # Things related to debugging #------------------------------------------------------------------------- def init_pdb(self): # Set calling of pdb on exceptions # self.call_pdb is a property self.call_pdb = self.pdb def _get_call_pdb(self): return self._call_pdb def _set_call_pdb(self,val): if val not in (0,1,False,True): raise ValueError('new call_pdb value must be boolean') # store value in instance self._call_pdb = val # notify the actual exception handlers self.InteractiveTB.call_pdb = val call_pdb = property(_get_call_pdb,_set_call_pdb,None, 'Control auto-activation of pdb at exceptions') def debugger(self,force=False): """Call the pdb debugger. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. """ if not (force or self.call_pdb): return if not hasattr(sys,'last_traceback'): error('No traceback has been produced, nothing to debug.') return self.InteractiveTB.debugger(force=True) #------------------------------------------------------------------------- # Things related to IPython's various namespaces #------------------------------------------------------------------------- default_user_namespaces = True def init_create_namespaces(self, user_module=None, user_ns=None): # Create the namespace where the user will operate. user_ns is # normally the only one used, and it is passed to the exec calls as # the locals argument. But we do carry a user_global_ns namespace # given as the exec 'globals' argument, This is useful in embedding # situations where the ipython shell opens in a context where the # distinction between locals and globals is meaningful. For # non-embedded contexts, it is just the same object as the user_ns dict. # FIXME. For some strange reason, __builtins__ is showing up at user # level as a dict instead of a module. This is a manual fix, but I # should really track down where the problem is coming from. Alex # Schmolck reported this problem first. # A useful post by Alex Martelli on this topic: # Re: inconsistent value from __builtins__ # Von: Alex Martelli <aleaxit@yahoo.com> # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends # Gruppen: comp.lang.python # Michael Hohn <hohn@hooknose.lbl.gov> wrote: # > >>> print type(builtin_check.get_global_binding('__builtins__')) # > <type 'dict'> # > >>> print type(__builtins__) # > <type 'module'> # > Is this difference in return value intentional? # Well, it's documented that '__builtins__' can be either a dictionary # or a module, and it's been that way for a long time. Whether it's # intentional (or sensible), I don't know. In any case, the idea is # that if you need to access the built-in namespace directly, you # should start with "import __builtin__" (note, no 's') which will # definitely give you a module. Yeah, it's somewhat confusing:-(. # These routines return a properly built module and dict as needed by # the rest of the code, and can also be used by extension writers to # generate properly initialized namespaces. if (user_ns is not None) or (user_module is not None): self.default_user_namespaces = False self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) # A record of hidden variables we have added to the user namespace, so # we can list later only variables defined in actual interactive use. self.user_ns_hidden = {} # Now that FakeModule produces a real module, we've run into a nasty # problem: after script execution (via %run), the module where the user # code ran is deleted. Now that this object is a true module (needed # so doctest and other tools work correctly), the Python module # teardown mechanism runs over it, and sets to None every variable # present in that module. Top-level references to objects from the # script survive, because the user_ns is updated with them. However, # calling functions defined in the script that use other things from # the script will fail, because the function's closure had references # to the original objects, which are now all None. So we must protect # these modules from deletion by keeping a cache. # # To avoid keeping stale modules around (we only need the one from the # last run), we use a dict keyed with the full path to the script, so # only the last version of the module is held in the cache. Note, # however, that we must cache the module *namespace contents* (their # __dict__). Because if we try to cache the actual modules, old ones # (uncached) could be destroyed while still holding references (such as # those held by GUI objects that tend to be long-lived)> # # The %reset command will flush this cache. See the cache_main_mod() # and clear_main_mod_cache() methods for details on use. # This is the cache used for 'main' namespaces self._main_mod_cache = {} # A table holding all the namespaces IPython deals with, so that # introspection facilities can search easily. self.ns_table = {'user_global':self.user_module.__dict__, 'user_local':self.user_ns, 'builtin':builtin_mod.__dict__ } def user_global_ns(self): return self.user_module.__dict__ def prepare_user_module(self, user_module=None, user_ns=None): """Prepare the module and namespace in which user code will be run. When IPython is started normally, both parameters are None: a new module is created automatically, and its __dict__ used as the namespace. If only user_module is provided, its __dict__ is used as the namespace. If only user_ns is provided, a dummy module is created, and user_ns becomes the global namespace. If both are provided (as they may be when embedding), user_ns is the local namespace, and user_module provides the global namespace. Parameters ---------- user_module : module, optional The current user module in which IPython is being run. If None, a clean module will be created. user_ns : dict, optional A namespace in which to run interactive commands. Returns ------- A tuple of user_module and user_ns, each properly initialised. """ if user_module is None and user_ns is not None: user_ns.setdefault("__name__", "__main__") user_module = DummyMod() user_module.__dict__ = user_ns if user_module is None: user_module = types.ModuleType("__main__", doc="Automatically created module for IPython interactive environment") # We must ensure that __builtin__ (without the final 's') is always # available and pointing to the __builtin__ *module*. For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html user_module.__dict__.setdefault('__builtin__', builtin_mod) user_module.__dict__.setdefault('__builtins__', builtin_mod) if user_ns is None: user_ns = user_module.__dict__ return user_module, user_ns def init_sys_modules(self): # We need to insert into sys.modules something that looks like a # module but which accesses the IPython namespace, for shelve and # pickle to work interactively. Normally they rely on getting # everything out of __main__, but for embedding purposes each IPython # instance has its own private namespace, so we can't go shoving # everything into __main__. # note, however, that we should only do this for non-embedded # ipythons, which really mimic the __main__.__dict__ with their own # namespace. Embedded instances, on the other hand, should not do # this because they need to manage the user local/global namespaces # only, but they live within a 'normal' __main__ (meaning, they # shouldn't overtake the execution environment of the script they're # embedded in). # This is overridden in the InteractiveShellEmbed subclass to a no-op. main_name = self.user_module.__name__ sys.modules[main_name] = self.user_module def init_user_ns(self): """Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this method. If they were not empty before, data will simply be added to them. """ # This function works in two parts: first we put a few things in # user_ns, and we sync that contents into user_ns_hidden so that these # initial variables aren't shown by %who. After the sync, we add the # rest of what we *do* want the user to see with %who even on a new # session (probably nothing, so they really only see their own stuff) # The user dict must *always* have a __builtin__ reference to the # Python standard __builtin__ namespace, which must be imported. # This is so that certain operations in prompt evaluation can be # reliably executed with builtins. Note that we can NOT use # __builtins__ (note the 's'), because that can either be a dict or a # module, and can even mutate at runtime, depending on the context # (Python makes no guarantees on it). In contrast, __builtin__ is # always a module object, though it must be explicitly imported. # For more details: # http://mail.python.org/pipermail/python-dev/2001-April/014068.html ns = {} # make global variables for user access to the histories ns['_ih'] = self.history_manager.input_hist_parsed ns['_oh'] = self.history_manager.output_hist ns['_dh'] = self.history_manager.dir_hist # user aliases to input and output histories. These shouldn't show up # in %who, as they can have very large reprs. ns['In'] = self.history_manager.input_hist_parsed ns['Out'] = self.history_manager.output_hist # Store myself as the public api!!! ns['get_ipython'] = self.get_ipython ns['exit'] = self.exiter ns['quit'] = self.exiter ns["open"] = _modified_open # Sync what we've added so far to user_ns_hidden so these aren't seen # by %who self.user_ns_hidden.update(ns) # Anything put into ns now would show up in %who. Think twice before # putting anything here, as we really want %who to show the user their # stuff, not our variables. # Finally, update the real user's namespace self.user_ns.update(ns) def all_ns_refs(self): """Get a list of references to all the namespace dictionaries in which IPython might store a user-created object. Note that this does not include the displayhook, which also caches objects from the output.""" return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ [m.__dict__ for m in self._main_mod_cache.values()] def reset(self, new_session=True, aggressive=False): """Clear all internal namespaces, and attempt to release references to user objects. If new_session is True, a new history session will be opened. """ # Clear histories self.history_manager.reset(new_session) # Reset counter used to index all histories if new_session: self.execution_count = 1 # Reset last execution result self.last_execution_succeeded = True self.last_execution_result = None # Flush cached output items if self.displayhook.do_full_cache: self.displayhook.flush() # The main execution namespaces must be cleared very carefully, # skipping the deletion of the builtin-related keys, because doing so # would cause errors in many object's __del__ methods. if self.user_ns is not self.user_global_ns: self.user_ns.clear() ns = self.user_global_ns drop_keys = set(ns.keys()) drop_keys.discard('__builtin__') drop_keys.discard('__builtins__') drop_keys.discard('__name__') for k in drop_keys: del ns[k] self.user_ns_hidden.clear() # Restore the user namespaces to minimal usability self.init_user_ns() if aggressive and not hasattr(self, "_sys_modules_keys"): print("Cannot restore sys.module, no snapshot") elif aggressive: print("culling sys module...") current_keys = set(sys.modules.keys()) for k in current_keys - self._sys_modules_keys: if k.startswith("multiprocessing"): continue del sys.modules[k] # Restore the default and user aliases self.alias_manager.clear_aliases() self.alias_manager.init_aliases() # Now define aliases that only make sense on the terminal, because they # need direct access to the console in a way that we can't emulate in # GUI or web frontend if os.name == 'posix': for cmd in ('clear', 'more', 'less', 'man'): if cmd not in self.magics_manager.magics['line']: self.alias_manager.soft_define_alias(cmd, cmd) # Flush the private list of module references kept for script # execution protection self.clear_main_mod_cache() def del_var(self, varname, by_name=False): """Delete a variable from the various namespaces, so that, as far as possible, we're not keeping any hidden references to it. Parameters ---------- varname : str The name of the variable to delete. by_name : bool If True, delete variables with the given name in each namespace. If False (default), find the variable in the user namespace, and delete references to it. """ if varname in ('__builtin__', '__builtins__'): raise ValueError("Refusing to delete %s" % varname) ns_refs = self.all_ns_refs if by_name: # Delete by name for ns in ns_refs: try: del ns[varname] except KeyError: pass else: # Delete by object try: obj = self.user_ns[varname] except KeyError as e: raise NameError("name '%s' is not defined" % varname) from e # Also check in output history ns_refs.append(self.history_manager.output_hist) for ns in ns_refs: to_delete = [n for n, o in ns.items() if o is obj] for name in to_delete: del ns[name] # Ensure it is removed from the last execution result if self.last_execution_result.result is obj: self.last_execution_result = None # displayhook keeps extra references, but not in a dictionary for name in ('_', '__', '___'): if getattr(self.displayhook, name) is obj: setattr(self.displayhook, name, None) def reset_selective(self, regex=None): """Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching variable names in the users namespaces. """ if regex is not None: try: m = re.compile(regex) except TypeError as e: raise TypeError('regex must be a string or compiled pattern') from e # Search for keys in each namespace that match the given regex # If a match is found, delete the key/value pair. for ns in self.all_ns_refs: for var in ns: if m.search(var): del ns[var] def push(self, variables, interactive=True): """Inject a group of variables into the IPython user namespace. Parameters ---------- variables : dict, str or list/tuple of str The variables to inject into the user's namespace. If a dict, a simple update is done. If a str, the string is assumed to have variable names separated by spaces. A list/tuple of str can also be used to give the variable names. If just the variable names are give (list/tuple/str) then the variable values looked up in the callers frame. interactive : bool If True (default), the variables will be listed with the ``who`` magic. """ vdict = None # We need a dict of name/value pairs to do namespace updates. if isinstance(variables, dict): vdict = variables elif isinstance(variables, (str, list, tuple)): if isinstance(variables, str): vlist = variables.split() else: vlist = variables vdict = {} cf = sys._getframe(1) for name in vlist: try: vdict[name] = eval(name, cf.f_globals, cf.f_locals) except: print('Could not get variable %s from %s' % (name,cf.f_code.co_name)) else: raise ValueError('variables must be a dict/str/list/tuple') # Propagate variables to user namespace self.user_ns.update(vdict) # And configure interactive visibility user_ns_hidden = self.user_ns_hidden if interactive: for name in vdict: user_ns_hidden.pop(name, None) else: user_ns_hidden.update(vdict) def drop_by_id(self, variables): """Remove a dict of variables from the user namespace, if they are the same as the values in the dictionary. This is intended for use by extensions: variables that they've added can be taken back out if they are unloaded, without removing any that the user has overwritten. Parameters ---------- variables : dict A dictionary mapping object names (as strings) to the objects. """ for name, obj in variables.items(): if name in self.user_ns and self.user_ns[name] is obj: del self.user_ns[name] self.user_ns_hidden.pop(name, None) #------------------------------------------------------------------------- # Things related to object introspection #------------------------------------------------------------------------- def _find_parts(oname: str) -> Tuple[bool, ListType[str]]: """ Given an object name, return a list of parts of this object name. Basically split on docs when using attribute access, and extract the value when using square bracket. For example foo.bar[3].baz[x] -> foo, bar, 3, baz, x Returns ------- parts_ok: bool wether we were properly able to parse parts. parts: list of str extracted parts """ raw_parts = oname.split(".") parts = [] parts_ok = True for p in raw_parts: if p.endswith("]"): var, *indices = p.split("[") if not var.isidentifier(): parts_ok = False break parts.append(var) for ind in indices: if ind[-1] != "]" and not is_integer_string(ind[:-1]): parts_ok = False break parts.append(ind[:-1]) continue if not p.isidentifier(): parts_ok = False parts.append(p) return parts_ok, parts def _ofind( self, oname: str, namespaces: Optional[Sequence[Tuple[str, AnyType]]] = None ) -> OInfo: """Find an object in the available namespaces. Returns ------- OInfo with fields: - ismagic - isalias - found - obj - namespac - parent Has special code to detect magic functions. """ oname = oname.strip() parts_ok, parts = self._find_parts(oname) if ( not oname.startswith(ESC_MAGIC) and not oname.startswith(ESC_MAGIC2) and not parts_ok ): return OInfo( ismagic=False, isalias=False, found=False, obj=None, namespace=None, parent=None, ) if namespaces is None: # Namespaces to search in: # Put them in a list. The order is important so that we # find things in the same order that Python finds them. namespaces = [ ('Interactive', self.user_ns), ('Interactive (global)', self.user_global_ns), ('Python builtin', builtin_mod.__dict__), ] ismagic = False isalias = False found = False ospace = None parent = None obj = None # Look for the given name by splitting it in parts. If the head is # found, then we look for all the remaining parts as members, and only # declare success if we can find them all. oname_parts = parts oname_head, oname_rest = oname_parts[0],oname_parts[1:] for nsname,ns in namespaces: try: obj = ns[oname_head] except KeyError: continue else: for idx, part in enumerate(oname_rest): try: parent = obj # The last part is looked up in a special way to avoid # descriptor invocation as it may raise or have side # effects. if idx == len(oname_rest) - 1: obj = self._getattr_property(obj, part) else: if is_integer_string(part): obj = obj[int(part)] else: obj = getattr(obj, part) except: # Blanket except b/c some badly implemented objects # allow __getattr__ to raise exceptions other than # AttributeError, which then crashes IPython. break else: # If we finish the for loop (no break), we got all members found = True ospace = nsname break # namespace loop # Try to see if it's magic if not found: obj = None if oname.startswith(ESC_MAGIC2): oname = oname.lstrip(ESC_MAGIC2) obj = self.find_cell_magic(oname) elif oname.startswith(ESC_MAGIC): oname = oname.lstrip(ESC_MAGIC) obj = self.find_line_magic(oname) else: # search without prefix, so run? will find %run? obj = self.find_line_magic(oname) if obj is None: obj = self.find_cell_magic(oname) if obj is not None: found = True ospace = 'IPython internal' ismagic = True isalias = isinstance(obj, Alias) # Last try: special-case some literals like '', [], {}, etc: if not found and oname_head in ["''",'""','[]','{}','()']: obj = eval(oname_head) found = True ospace = 'Interactive' return OInfo( obj=obj, found=found, parent=parent, ismagic=ismagic, isalias=isalias, namespace=ospace, ) def _getattr_property(obj, attrname): """Property-aware getattr to use in object finding. If attrname represents a property, return it unevaluated (in case it has side effects or raises an error. """ if not isinstance(obj, type): try: # `getattr(type(obj), attrname)` is not guaranteed to return # `obj`, but does so for property: # # property.__get__(self, None, cls) -> self # # The universal alternative is to traverse the mro manually # searching for attrname in class dicts. if is_integer_string(attrname): return obj[int(attrname)] else: attr = getattr(type(obj), attrname) except AttributeError: pass else: # This relies on the fact that data descriptors (with both # __get__ & __set__ magic methods) take precedence over # instance-level attributes: # # class A(object): # @property # def foobar(self): return 123 # a = A() # a.__dict__['foobar'] = 345 # a.foobar # == 123 # # So, a property may be returned right away. if isinstance(attr, property): return attr # Nothing helped, fall back. return getattr(obj, attrname) def _object_find(self, oname, namespaces=None) -> OInfo: """Find an object and return a struct with info about it.""" return self._ofind(oname, namespaces) def _inspect(self, meth, oname, namespaces=None, **kw): """Generic interface to the inspector system. This function is meant to be called by pdef, pdoc & friends. """ info: OInfo = self._object_find(oname, namespaces) docformat = ( sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None ) if info.found or hasattr(info.parent, oinspect.HOOK_NAME): pmethod = getattr(self.inspector, meth) # TODO: only apply format_screen to the plain/text repr of the mime # bundle. formatter = format_screen if info.ismagic else docformat if meth == 'pdoc': pmethod(info.obj, oname, formatter) elif meth == 'pinfo': pmethod( info.obj, oname, formatter, info, enable_html_pager=self.enable_html_pager, **kw, ) else: pmethod(info.obj, oname) else: print('Object `%s` not found.' % oname) return 'not found' # so callers can take other action def object_inspect(self, oname, detail_level=0): """Get object info about oname""" with self.builtin_trap: info = self._object_find(oname) if info.found: return self.inspector.info(info.obj, oname, info=info, detail_level=detail_level ) else: return oinspect.object_info(name=oname, found=False) def object_inspect_text(self, oname, detail_level=0): """Get object info as formatted text""" return self.object_inspect_mime(oname, detail_level)['text/plain'] def object_inspect_mime(self, oname, detail_level=0, omit_sections=()): """Get object info as a mimebundle of formatted representations. A mimebundle is a dictionary, keyed by mime-type. It must always have the key `'text/plain'`. """ with self.builtin_trap: info = self._object_find(oname) if info.found: docformat = ( sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None ) return self.inspector._get_info( info.obj, oname, info=info, detail_level=detail_level, formatter=docformat, omit_sections=omit_sections, ) else: raise KeyError(oname) #------------------------------------------------------------------------- # Things related to history management #------------------------------------------------------------------------- def init_history(self): """Sets up the command history, and starts regular autosaves.""" self.history_manager = HistoryManager(shell=self, parent=self) self.configurables.append(self.history_manager) #------------------------------------------------------------------------- # Things related to exception handling and tracebacks (not debugging) #------------------------------------------------------------------------- debugger_cls = InterruptiblePdb def init_traceback_handlers(self, custom_exceptions): # Syntax error handler. self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) # The interactive one is initialized with an offset, meaning we always # want to remove the topmost item in the traceback, which is our own # internal code. Valid modes: ['Plain','Context','Verbose','Minimal'] self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', color_scheme='NoColor', tb_offset = 1, debugger_cls=self.debugger_cls, parent=self) # The instance will store a pointer to the system-wide exception hook, # so that runtime code (such as magics) can access it. This is because # during the read-eval loop, it may get temporarily overwritten. self.sys_excepthook = sys.excepthook # and add any custom exception handlers the user may have specified self.set_custom_exc(*custom_exceptions) # Set the exception mode self.InteractiveTB.set_mode(mode=self.xmode) def set_custom_exc(self, exc_tuple, handler): """set_custom_exc(exc_tuple, handler) Set a custom exception handler, which will be called if any of the exceptions in exc_tuple occur in the mainloop (specifically, in the run_code() method). Parameters ---------- exc_tuple : tuple of exception classes A *tuple* of exception classes, for which to call the defined handler. It is very important that you use a tuple, and NOT A LIST here, because of the way Python's except statement works. If you only want to trap a single exception, use a singleton tuple:: exc_tuple == (MyCustomException,) handler : callable handler must have the following signature:: def my_handler(self, etype, value, tb, tb_offset=None): ... return structured_traceback Your handler must return a structured traceback (a list of strings), or None. This will be made into an instance method (via types.MethodType) of IPython itself, and it will be called if any of the exceptions listed in the exc_tuple are caught. If the handler is None, an internal basic one is used, which just prints basic info. To protect IPython from crashes, if your handler ever raises an exception or returns an invalid result, it will be immediately disabled. Notes ----- WARNING: by putting in your own exception handler into IPython's main execution loop, you run a very good chance of nasty crashes. This facility should only be used if you really know what you are doing. """ if not isinstance(exc_tuple, tuple): raise TypeError("The custom exceptions must be given as a tuple.") def dummy_handler(self, etype, value, tb, tb_offset=None): print('*** Simple custom exception handler ***') print('Exception type :', etype) print('Exception value:', value) print('Traceback :', tb) def validate_stb(stb): """validate structured traceback return type return type of CustomTB *should* be a list of strings, but allow single strings or None, which are harmless. This function will *always* return a list of strings, and will raise a TypeError if stb is inappropriate. """ msg = "CustomTB must return list of strings, not %r" % stb if stb is None: return [] elif isinstance(stb, str): return [stb] elif not isinstance(stb, list): raise TypeError(msg) # it's a list for line in stb: # check every element if not isinstance(line, str): raise TypeError(msg) return stb if handler is None: wrapped = dummy_handler else: def wrapped(self,etype,value,tb,tb_offset=None): """wrap CustomTB handler, to protect IPython from user code This makes it harder (but not impossible) for custom exception handlers to crash IPython. """ try: stb = handler(self,etype,value,tb,tb_offset=tb_offset) return validate_stb(stb) except: # clear custom handler immediately self.set_custom_exc((), None) print("Custom TB Handler failed, unregistering", file=sys.stderr) # show the exception in handler first stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) print(self.InteractiveTB.stb2text(stb)) print("The original exception:") stb = self.InteractiveTB.structured_traceback( (etype,value,tb), tb_offset=tb_offset ) return stb self.CustomTB = types.MethodType(wrapped,self) self.custom_exceptions = exc_tuple def excepthook(self, etype, value, tb): """One more defense for GUI apps that call sys.excepthook. GUI frameworks like wxPython trap exceptions and call sys.excepthook themselves. I guess this is a feature that enables them to keep running after exceptions that would otherwise kill their mainloop. This is a bother for IPython which expects to catch all of the program exceptions with a try: except: statement. Normally, IPython sets sys.excepthook to a CrashHandler instance, so if any app directly invokes sys.excepthook, it will look to the user like IPython crashed. In order to work around this, we can disable the CrashHandler and replace it with this excepthook instead, which prints a regular traceback using our InteractiveTB. In this fashion, apps which call sys.excepthook will generate a regular-looking exception from IPython, and the CrashHandler will only be triggered by real IPython crashes. This hook should be used sparingly, only in places which are not likely to be true IPython errors. """ self.showtraceback((etype, value, tb), tb_offset=0) def _get_exc_info(self, exc_tuple=None): """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information """ if exc_tuple is None: etype, value, tb = sys.exc_info() else: etype, value, tb = exc_tuple if etype is None: if hasattr(sys, 'last_type'): etype, value, tb = sys.last_type, sys.last_value, \ sys.last_traceback if etype is None: raise ValueError("No exception to find") # Now store the exception info in sys.last_type etc. # WARNING: these variables are somewhat deprecated and not # necessarily safe to use in a threaded environment, but tools # like pdb depend on their existence, so let's set them. If we # find problems in the field, we'll need to revisit their use. sys.last_type = etype sys.last_value = value sys.last_traceback = tb return etype, value, tb def show_usage_error(self, exc): """Show a short message for UsageErrors These are special exceptions that shouldn't show a traceback. """ print("UsageError: %s" % exc, file=sys.stderr) def get_exception_only(self, exc_tuple=None): """ Return as a string (ending with a newline) the exception that just occurred, without any traceback. """ etype, value, tb = self._get_exc_info(exc_tuple) msg = traceback.format_exception_only(etype, value) return ''.join(msg) def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, exception_only=False, running_compiled_code=False): """Display the exception that just occurred. If nothing is known about the exception, this is the method which should be used throughout the code for presenting user tracebacks, rather than directly invoking the InteractiveTB object. A specific showsyntaxerror() also exists, but this method can take care of calling it if needed, so unless you are explicitly catching a SyntaxError exception, don't try to analyze the stack manually and simply call this method.""" try: try: etype, value, tb = self._get_exc_info(exc_tuple) except ValueError: print('No traceback available to show.', file=sys.stderr) return if issubclass(etype, SyntaxError): # Though this won't be called by syntax errors in the input # line, there may be SyntaxError cases with imported code. self.showsyntaxerror(filename, running_compiled_code) elif etype is UsageError: self.show_usage_error(value) else: if exception_only: stb = ['An exception has occurred, use %tb to see ' 'the full traceback.\n'] stb.extend(self.InteractiveTB.get_exception_only(etype, value)) else: try: # Exception classes can customise their traceback - we # use this in IPython.parallel for exceptions occurring # in the engines. This should return a list of strings. if hasattr(value, "_render_traceback_"): stb = value._render_traceback_() else: stb = self.InteractiveTB.structured_traceback( etype, value, tb, tb_offset=tb_offset ) except Exception: print( "Unexpected exception formatting exception. Falling back to standard exception" ) traceback.print_exc() return None self._showtraceback(etype, value, stb) if self.call_pdb: # drop into debugger self.debugger(force=True) return # Actually show the traceback self._showtraceback(etype, value, stb) except KeyboardInterrupt: print('\n' + self.get_exception_only(), file=sys.stderr) def _showtraceback(self, etype, evalue, stb: str): """Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel. """ val = self.InteractiveTB.stb2text(stb) try: print(val) except UnicodeEncodeError: print(val.encode("utf-8", "backslashreplace").decode()) def showsyntaxerror(self, filename=None, running_compiled_code=False): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), longer stack trace will be displayed. """ etype, value, last_traceback = self._get_exc_info() if filename and issubclass(etype, SyntaxError): try: value.filename = filename except: # Not the format we expect; leave it alone pass # If the error occurred when executing compiled code, we should provide full stacktrace. elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] stb = self.SyntaxTB.structured_traceback(etype, value, elist) self._showtraceback(etype, value, stb) # This is overridden in TerminalInteractiveShell to show a message about # the %paste magic. def showindentationerror(self): """Called by _run_cell when there's an IndentationError in code entered at the prompt. This is overridden in TerminalInteractiveShell to show a message about the %paste magic.""" self.showsyntaxerror() def set_next_input(self, s, replace=False): """ Sets the 'default' input string for the next command line. Example:: In [1]: _ip.set_next_input("Hello Word") In [2]: Hello Word_ # cursor is here """ self.rl_next_input = s def _indent_current_str(self): """return the current level of indentation as a string""" return self.input_splitter.get_indent_spaces() * ' ' #------------------------------------------------------------------------- # Things related to text completion #------------------------------------------------------------------------- def init_completer(self): """Initialize the completion machinery. This creates completion machinery that can be used by client code, either interactively in-process (typically triggered by the readline library), programmatically (such as in test suites) or out-of-process (typically over the network by remote frontends). """ from IPython.core.completer import IPCompleter from IPython.core.completerlib import ( cd_completer, magic_run_completer, module_completer, reset_completer, ) self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, parent=self, ) self.configurables.append(self.Completer) # Add custom completers to the basic ones built into IPCompleter sdisp = self.strdispatchers.get('complete_command', StrDispatch()) self.strdispatchers['complete_command'] = sdisp self.Completer.custom_completers = sdisp self.set_hook('complete_command', module_completer, str_key = 'import') self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', module_completer, str_key = '%aimport') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', cd_completer, str_key = '%cd') self.set_hook('complete_command', reset_completer, str_key = '%reset') def complete(self, text, line=None, cursor_pos=None): """Return the completed text and a list of completions. Parameters ---------- text : string A string of text to be completed on. It can be given as empty and instead a line/position pair are given. In this case, the completer itself will split the line like readline does. line : string, optional The complete line that text is part of. cursor_pos : int, optional The position of the cursor on the input line. Returns ------- text : string The actual text that was completed. matches : list A sorted list with all possible completions. Notes ----- The optional arguments allow the completion to take more context into account, and are part of the low-level completion API. This is a wrapper around the completion mechanism, similar to what readline does at the command line when the TAB key is hit. By exposing it as a method, it can be used by other non-readline environments (such as GUIs) for text completion. Examples -------- In [1]: x = 'hello' In [2]: _ip.complete('x.l') Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) """ # Inject names into __builtin__ so we can complete on the added names. with self.builtin_trap: return self.Completer.complete(text, line, cursor_pos) def set_custom_completer(self, completer, pos=0) -> None: """Adds a new custom completer function. The position argument (defaults to 0) is the index in the completers list where you want the completer to be inserted. `completer` should have the following signature:: def completion(self: Completer, text: string) -> List[str]: raise NotImplementedError It will be bound to the current Completer instance and pass some text and return a list with current completions to suggest to the user. """ newcomp = types.MethodType(completer, self.Completer) self.Completer.custom_matchers.insert(pos,newcomp) def set_completer_frame(self, frame=None): """Set the frame of the completer.""" if frame: self.Completer.namespace = frame.f_locals self.Completer.global_namespace = frame.f_globals else: self.Completer.namespace = self.user_ns self.Completer.global_namespace = self.user_global_ns #------------------------------------------------------------------------- # Things related to magics #------------------------------------------------------------------------- def init_magics(self): from IPython.core import magics as m self.magics_manager = magic.MagicsManager(shell=self, parent=self, user_magics=m.UserMagics(self)) self.configurables.append(self.magics_manager) # Expose as public API from the magics manager self.register_magics = self.magics_manager.register self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, m.NamespaceMagics, m.OSMagics, m.PackagingMagics, m.PylabMagics, m.ScriptMagics, ) self.register_magics(m.AsyncMagics) # Register Magic Aliases mman = self.magics_manager # FIXME: magic aliases should be defined by the Magics classes # or in MagicsManager, not here mman.register_alias('ed', 'edit') mman.register_alias('hist', 'history') mman.register_alias('rep', 'recall') mman.register_alias('SVG', 'svg', 'cell') mman.register_alias('HTML', 'html', 'cell') mman.register_alias('file', 'writefile', 'cell') # FIXME: Move the color initialization to the DisplayHook, which # should be split into a prompt manager and displayhook. We probably # even need a centralize colors management object. self.run_line_magic('colors', self.colors) # Defined here so that it's included in the documentation def register_magic_function(self, func, magic_kind='line', magic_name=None): self.magics_manager.register_function( func, magic_kind=magic_kind, magic_name=magic_name ) def _find_with_lazy_load(self, /, type_, magic_name: str): """ Try to find a magic potentially lazy-loading it. Parameters ---------- type_: "line"|"cell" the type of magics we are trying to find/lazy load. magic_name: str The name of the magic we are trying to find/lazy load Note that this may have any side effects """ finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_] fn = finder(magic_name) if fn is not None: return fn lazy = self.magics_manager.lazy_magics.get(magic_name) if lazy is None: return None self.run_line_magic("load_ext", lazy) res = finder(magic_name) return res def run_line_magic(self, magic_name: str, line, _stack_depth=1): """Execute the given line magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the input line as a single string. _stack_depth : int If run_line_magic() is called from magic() then _stack_depth=2. This is added to ensure backward compatibility for use of 'get_ipython().magic()' """ fn = self._find_with_lazy_load("line", magic_name) if fn is None: lazy = self.magics_manager.lazy_magics.get(magic_name) if lazy: self.run_line_magic("load_ext", lazy) fn = self.find_line_magic(magic_name) if fn is None: cm = self.find_cell_magic(magic_name) etpl = "Line magic function `%%%s` not found%s." extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' 'did you mean that instead?)' % magic_name ) raise UsageError(etpl % (magic_name, extra)) else: # Note: this is the distance in the stack to the user's frame. # This will need to be updated if the internal calling logic gets # refactored, or else we'll be expanding the wrong variables. # Determine stack_depth depending on where run_line_magic() has been called stack_depth = _stack_depth if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): # magic has opted out of var_expand magic_arg_s = line else: magic_arg_s = self.var_expand(line, stack_depth) # Put magic args in a list so we can call with f(*a) syntax args = [magic_arg_s] kwargs = {} # Grab local namespace if we need it: if getattr(fn, "needs_local_scope", False): kwargs['local_ns'] = self.get_local_scope(stack_depth) with self.builtin_trap: result = fn(*args, **kwargs) # The code below prevents the output from being displayed # when using magics with decodator @output_can_be_silenced # when the last Python token in the expression is a ';'. if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): if DisplayHook.semicolon_at_end_of_expression(magic_arg_s): return None return result def get_local_scope(self, stack_depth): """Get local scope at given stack depth. Parameters ---------- stack_depth : int Depth relative to calling frame """ return sys._getframe(stack_depth + 1).f_locals def run_cell_magic(self, magic_name, line, cell): """Execute the given cell magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the first input line as a single string. cell : str The body of the cell as a (possibly multiline) string. """ fn = self._find_with_lazy_load("cell", magic_name) if fn is None: lm = self.find_line_magic(magic_name) etpl = "Cell magic `%%{0}` not found{1}." extra = '' if lm is None else (' (But line magic `%{0}` exists, ' 'did you mean that instead?)'.format(magic_name)) raise UsageError(etpl.format(magic_name, extra)) elif cell == '': message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) if self.find_line_magic(magic_name) is not None: message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) raise UsageError(message) else: # Note: this is the distance in the stack to the user's frame. # This will need to be updated if the internal calling logic gets # refactored, or else we'll be expanding the wrong variables. stack_depth = 2 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False): # magic has opted out of var_expand magic_arg_s = line else: magic_arg_s = self.var_expand(line, stack_depth) kwargs = {} if getattr(fn, "needs_local_scope", False): kwargs['local_ns'] = self.user_ns with self.builtin_trap: args = (magic_arg_s, cell) result = fn(*args, **kwargs) # The code below prevents the output from being displayed # when using magics with decodator @output_can_be_silenced # when the last Python token in the expression is a ';'. if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): if DisplayHook.semicolon_at_end_of_expression(cell): return None return result def find_line_magic(self, magic_name): """Find and return a line magic by name. Returns None if the magic isn't found.""" return self.magics_manager.magics['line'].get(magic_name) def find_cell_magic(self, magic_name): """Find and return a cell magic by name. Returns None if the magic isn't found.""" return self.magics_manager.magics['cell'].get(magic_name) def find_magic(self, magic_name, magic_kind='line'): """Find and return a magic of the given type by name. Returns None if the magic isn't found.""" return self.magics_manager.magics[magic_kind].get(magic_name) def magic(self, arg_s): """ DEPRECATED Deprecated since IPython 0.13 (warning added in 8.1), use run_line_magic(magic_name, parameter_s). Call a magic function by name. Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic. magic('name -opt foo bar') is equivalent to typing at the ipython prompt: In[1]: %name -opt foo bar To call a magic without arguments, simply use magic('name'). This provides a proper Python function to call IPython's magics in any valid Python code you can type at the interpreter, including loops and compound statements. """ warnings.warn( "`magic(...)` is deprecated since IPython 0.13 (warning added in " "8.1), use run_line_magic(magic_name, parameter_s).", DeprecationWarning, stacklevel=2, ) # TODO: should we issue a loud deprecation warning here? magic_name, _, magic_arg_s = arg_s.partition(' ') magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) #------------------------------------------------------------------------- # Things related to macros #------------------------------------------------------------------------- def define_macro(self, name, themacro): """Define a new macro Parameters ---------- name : str The name of the macro. themacro : str or Macro The action to do upon invoking the macro. If a string, a new Macro object is created by passing the string to it. """ from IPython.core import macro if isinstance(themacro, str): themacro = macro.Macro(themacro) if not isinstance(themacro, macro.Macro): raise ValueError('A macro must be a string or a Macro instance.') self.user_ns[name] = themacro #------------------------------------------------------------------------- # Things related to the running of system commands #------------------------------------------------------------------------- def system_piped(self, cmd): """Call the given cmd in a subprocess, piping stdout/err Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. Should not be a command that expects input other than simple text. """ if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test # We do not support backgrounding processes because we either use # pexpect or pipes to read from. Users can always just call # os.system() or use ip.system=ip.system_raw # if they really want a background process. raise OSError("Background processes not supported.") # we explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) def system_raw(self, cmd): """Call the given cmd in a subprocess using os.system on Windows or subprocess.call using the system shell on other platforms. Parameters ---------- cmd : str Command to execute. """ cmd = self.var_expand(cmd, depth=1) # warn if there is an IPython magic alternative. main_cmd = cmd.split()[0] has_magic_alternatives = ("pip", "conda", "cd") if main_cmd in has_magic_alternatives: warnings.warn( ( "You executed the system command !{0} which may not work " "as expected. Try the IPython magic %{0} instead." ).format(main_cmd) ) # protect os.system from UNC paths on Windows, which it can't handle: if sys.platform == 'win32': from IPython.utils._process_win32 import AvoidUNCPath with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) try: ec = os.system(cmd) except KeyboardInterrupt: print('\n' + self.get_exception_only(), file=sys.stderr) ec = -2 else: # For posix the result of the subprocess.call() below is an exit # code, which by convention is zero for success, positive for # program failure. Exit codes above 128 are reserved for signals, # and the formula for converting a signal to an exit code is usually # signal_number+128. To more easily differentiate between exit # codes and signals, ipython uses negative numbers. For instance # since control-c is signal 2 but exit code 130, ipython's # _exit_code variable will read -2. Note that some shells like # csh and fish don't follow sh/bash conventions for exit codes. executable = os.environ.get('SHELL', None) try: # Use env shell instead of default /bin/sh ec = subprocess.call(cmd, shell=True, executable=executable) except KeyboardInterrupt: # intercept control-C; a long traceback is not useful here print('\n' + self.get_exception_only(), file=sys.stderr) ec = 130 if ec > 128: ec = -(ec - 128) # We explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. Note the semantics # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, # but raising SystemExit(_exit_code) will give status 254! self.user_ns['_exit_code'] = ec # use piped system by default, because it is better behaved system = system_piped def getoutput(self, cmd, split=True, depth=0): """Get output (possibly including stderr) from a subprocess. Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. split : bool, optional If True, split the output into an IPython SList. Otherwise, an IPython LSString is returned. These are objects similar to normal lists and strings, with a few convenience attributes for easier manipulation of line-based output. You can use '?' on them for details. depth : int, optional How many frames above the caller are the local variables which should be expanded in the command string? The default (0) assumes that the expansion variables are in the stack frame calling this function. """ if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test raise OSError("Background processes not supported.") out = getoutput(self.var_expand(cmd, depth=depth+1)) if split: out = SList(out.splitlines()) else: out = LSString(out) return out #------------------------------------------------------------------------- # Things related to aliases #------------------------------------------------------------------------- def init_alias(self): self.alias_manager = AliasManager(shell=self, parent=self) self.configurables.append(self.alias_manager) #------------------------------------------------------------------------- # Things related to extensions #------------------------------------------------------------------------- def init_extension_manager(self): self.extension_manager = ExtensionManager(shell=self, parent=self) self.configurables.append(self.extension_manager) #------------------------------------------------------------------------- # Things related to payloads #------------------------------------------------------------------------- def init_payload(self): self.payload_manager = PayloadManager(parent=self) self.configurables.append(self.payload_manager) #------------------------------------------------------------------------- # Things related to the prefilter #------------------------------------------------------------------------- def init_prefilter(self): self.prefilter_manager = PrefilterManager(shell=self, parent=self) self.configurables.append(self.prefilter_manager) # Ultimately this will be refactored in the new interpreter code, but # for now, we should expose the main prefilter method (there's legacy # code out there that may rely on this). self.prefilter = self.prefilter_manager.prefilter_lines def auto_rewrite_input(self, cmd): """Print to the screen the rewritten form of the user's command. This shows visual feedback by rewriting input lines that cause automatic calling to kick in, like:: /f x into:: ------> f(x) after the user's input prompt. This helps the user understand that the input line was transformed automatically by IPython. """ if not self.show_rewritten_input: return # This is overridden in TerminalInteractiveShell to use fancy prompts print("------> " + cmd) #------------------------------------------------------------------------- # Things related to extracting values/expressions from kernel and user_ns #------------------------------------------------------------------------- def _user_obj_error(self): """return simple exception dict for use in user_expressions """ etype, evalue, tb = self._get_exc_info() stb = self.InteractiveTB.get_exception_only(etype, evalue) exc_info = { "status": "error", "traceback": stb, "ename": etype.__name__, "evalue": py3compat.safe_unicode(evalue), } return exc_info def _format_user_obj(self, obj): """format a user object to display dict for use in user_expressions """ data, md = self.display_formatter.format(obj) value = { 'status' : 'ok', 'data' : data, 'metadata' : md, } return value def user_expressions(self, expressions): """Evaluate a dict of expressions in the user's namespace. Parameters ---------- expressions : dict A dict with string keys and string values. The expression values should be valid Python expressions, each of which will be evaluated in the user namespace. Returns ------- A dict, keyed like the input expressions dict, with the rich mime-typed display_data of each value. """ out = {} user_ns = self.user_ns global_ns = self.user_global_ns for key, expr in expressions.items(): try: value = self._format_user_obj(eval(expr, global_ns, user_ns)) except: value = self._user_obj_error() out[key] = value return out #------------------------------------------------------------------------- # Things related to the running of code #------------------------------------------------------------------------- def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec(cmd, self.user_global_ns, self.user_ns) def ev(self, expr): """Evaluate python expression expr in user namespace. Returns the result of evaluation """ with self.builtin_trap: return eval(expr, self.user_global_ns, self.user_ns) def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): """A safe version of the builtin execfile(). This version will never throw an exception, but instead print helpful error messages to the screen. This only works on pure Python files with the .py extension. Parameters ---------- fname : string The name of the file to be executed. *where : tuple One or two namespaces, passed to execfile() as (globals,locals). If only one is given, it is passed as both. exit_ignore : bool (False) If True, then silence SystemExit for non-zero status (it is always silenced for zero status, as it is so common). raise_exceptions : bool (False) If True raise exceptions everywhere. Meant for testing. shell_futures : bool (False) If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. """ fname = Path(fname).expanduser().resolve() # Make sure we can open the file try: with fname.open("rb"): pass except: warn('Could not open file <%s> for safe execution.' % fname) return # Find things also in current directory. This is needed to mimic the # behavior of running a script from the system command line, where # Python inserts the script's directory into sys.path dname = str(fname.parent) with prepended_to_syspath(dname), self.builtin_trap: try: glob, loc = (where + (None, ))[:2] py3compat.execfile( fname, glob, loc, self.compile if shell_futures else None) except SystemExit as status: # If the call was made with 0 or None exit status (sys.exit(0) # or sys.exit() ), don't bother showing a traceback, as both of # these are considered normal by the OS: # > python -c'import sys;sys.exit(0)'; echo $? # 0 # > python -c'import sys;sys.exit()'; echo $? # 0 # For other exit status, we show the exception unless # explicitly silenced, but only in short form. if status.code: if raise_exceptions: raise if not exit_ignore: self.showtraceback(exception_only=True) except: if raise_exceptions: raise # tb offset is 2 because we wrap execfile self.showtraceback(tb_offset=2) def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy or .ipynb extension. shell_futures : bool (False) If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. raise_exceptions : bool (False) If True raise exceptions everywhere. Meant for testing. """ fname = Path(fname).expanduser().resolve() # Make sure we can open the file try: with fname.open("rb"): pass except: warn('Could not open file <%s> for safe execution.' % fname) return # Find things also in current directory. This is needed to mimic the # behavior of running a script from the system command line, where # Python inserts the script's directory into sys.path dname = str(fname.parent) def get_cells(): """generator for sequence of code blocks to run""" if fname.suffix == ".ipynb": from nbformat import read nb = read(fname, as_version=4) if not nb.cells: return for cell in nb.cells: if cell.cell_type == 'code': yield cell.source else: yield fname.read_text(encoding="utf-8") with prepended_to_syspath(dname): try: for cell in get_cells(): result = self.run_cell(cell, silent=True, shell_futures=shell_futures) if raise_exceptions: result.raise_error() elif not result.success: break except: if raise_exceptions: raise self.showtraceback() warn('Unknown failure executing file: <%s>' % fname) def safe_run_module(self, mod_name, where): """A safe version of runpy.run_module(). This version will never throw an exception, but instead print helpful error messages to the screen. `SystemExit` exceptions with status code 0 or None are ignored. Parameters ---------- mod_name : string The name of the module to be executed. where : dict The globals namespace. """ try: try: where.update( runpy.run_module(str(mod_name), run_name="__main__", alter_sys=True) ) except SystemExit as status: if status.code: raise except: self.showtraceback() warn('Unknown failure executing module: <%s>' % mod_name) def run_cell( self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None, ): """Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False. silent : bool If True, avoid side-effects, such as implicit displayhooks and and logging. silent=True forces store_history=False. shell_futures : bool If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. Returns ------- result : :class:`ExecutionResult` """ result = None try: result = self._run_cell( raw_cell, store_history, silent, shell_futures, cell_id ) finally: self.events.trigger('post_execute') if not silent: self.events.trigger('post_run_cell', result) return result def _run_cell( self, raw_cell: str, store_history: bool, silent: bool, shell_futures: bool, cell_id: str, ) -> ExecutionResult: """Internal method to run a complete IPython cell.""" # we need to avoid calling self.transform_cell multiple time on the same thing # so we need to store some results: preprocessing_exc_tuple = None try: transformed_cell = self.transform_cell(raw_cell) except Exception: transformed_cell = raw_cell preprocessing_exc_tuple = sys.exc_info() assert transformed_cell is not None coro = self.run_cell_async( raw_cell, store_history=store_history, silent=silent, shell_futures=shell_futures, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple, cell_id=cell_id, ) # run_cell_async is async, but may not actually need an eventloop. # when this is the case, we want to run it using the pseudo_sync_runner # so that code can invoke eventloops (for example via the %run , and # `%paste` magic. if self.trio_runner: runner = self.trio_runner elif self.should_run_async( raw_cell, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple, ): runner = self.loop_runner else: runner = _pseudo_sync_runner try: result = runner(coro) except BaseException as e: info = ExecutionInfo( raw_cell, store_history, silent, shell_futures, cell_id ) result = ExecutionResult(info) result.error_in_exec = e self.showtraceback(running_compiled_code=True) finally: return result def should_run_async( self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None ) -> bool: """Return whether a cell should be run asynchronously via a coroutine runner Parameters ---------- raw_cell : str The code to be executed Returns ------- result: bool Whether the code needs to be run with a coroutine runner or not .. versionadded:: 7.0 """ if not self.autoawait: return False if preprocessing_exc_tuple is not None: return False assert preprocessing_exc_tuple is None if transformed_cell is None: warnings.warn( "`should_run_async` will not call `transform_cell`" " automatically in the future. Please pass the result to" " `transformed_cell` argument and any exception that happen" " during the" "transform in `preprocessing_exc_tuple` in" " IPython 7.17 and above.", DeprecationWarning, stacklevel=2, ) try: cell = self.transform_cell(raw_cell) except Exception: # any exception during transform will be raised # prior to execution return False else: cell = transformed_cell return _should_be_async(cell) async def run_cell_async( self, raw_cell: str, store_history=False, silent=False, shell_futures=True, *, transformed_cell: Optional[str] = None, preprocessing_exc_tuple: Optional[AnyType] = None, cell_id=None, ) -> ExecutionResult: """Run a complete IPython cell asynchronously. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False. silent : bool If True, avoid side-effects, such as implicit displayhooks and and logging. silent=True forces store_history=False. shell_futures : bool If True, the code will share future statements with the interactive shell. It will both be affected by previous __future__ imports, and any __future__ imports in the code will affect the shell. If False, __future__ imports are not shared in either direction. transformed_cell: str cell that was passed through transformers preprocessing_exc_tuple: trace if the transformation failed. Returns ------- result : :class:`ExecutionResult` .. versionadded:: 7.0 """ info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id) result = ExecutionResult(info) if (not raw_cell) or raw_cell.isspace(): self.last_execution_succeeded = True self.last_execution_result = result return result if silent: store_history = False if store_history: result.execution_count = self.execution_count def error_before_exec(value): if store_history: self.execution_count += 1 result.error_before_exec = value self.last_execution_succeeded = False self.last_execution_result = result return result self.events.trigger('pre_execute') if not silent: self.events.trigger('pre_run_cell', info) if transformed_cell is None: warnings.warn( "`run_cell_async` will not call `transform_cell`" " automatically in the future. Please pass the result to" " `transformed_cell` argument and any exception that happen" " during the" "transform in `preprocessing_exc_tuple` in" " IPython 7.17 and above.", DeprecationWarning, stacklevel=2, ) # If any of our input transformation (input_transformer_manager or # prefilter_manager) raises an exception, we store it in this variable # so that we can display the error after logging the input and storing # it in the history. try: cell = self.transform_cell(raw_cell) except Exception: preprocessing_exc_tuple = sys.exc_info() cell = raw_cell # cell has to exist so it can be stored/logged else: preprocessing_exc_tuple = None else: if preprocessing_exc_tuple is None: cell = transformed_cell else: cell = raw_cell # Do NOT store paste/cpaste magic history if "get_ipython().run_line_magic(" in cell and "paste" in cell: store_history = False # Store raw and processed history if store_history: self.history_manager.store_inputs(self.execution_count, cell, raw_cell) if not silent: self.logger.log(cell, raw_cell) # Display the exception if input processing failed. if preprocessing_exc_tuple is not None: self.showtraceback(preprocessing_exc_tuple) if store_history: self.execution_count += 1 return error_before_exec(preprocessing_exc_tuple[1]) # Our own compiler remembers the __future__ environment. If we want to # run code with a separate __future__ environment, use the default # compiler compiler = self.compile if shell_futures else self.compiler_class() _run_async = False with self.builtin_trap: cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell) with self.display_trap: # Compile to bytecode try: code_ast = compiler.ast_parse(cell, filename=cell_name) except self.custom_exceptions as e: etype, value, tb = sys.exc_info() self.CustomTB(etype, value, tb) return error_before_exec(e) except IndentationError as e: self.showindentationerror() return error_before_exec(e) except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError) as e: self.showsyntaxerror() return error_before_exec(e) # Apply AST transformations try: code_ast = self.transform_ast(code_ast) except InputRejected as e: self.showtraceback() return error_before_exec(e) # Give the displayhook a reference to our ExecutionResult so it # can fill in the output value. self.displayhook.exec_result = result # Execute the user code interactivity = "none" if silent else self.ast_node_interactivity has_raised = await self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity, compiler=compiler, result=result) self.last_execution_succeeded = not has_raised self.last_execution_result = result # Reset this so later displayed values do not modify the # ExecutionResult self.displayhook.exec_result = None if store_history: # Write output to the database. Does nothing unless # history output logging is enabled. self.history_manager.store_output(self.execution_count) # Each cell is a *single* input, regardless of how many lines it has self.execution_count += 1 return result def transform_cell(self, raw_cell): """Transform an input cell before parsing it. Static transformations, implemented in IPython.core.inputtransformer2, deal with things like ``%magic`` and ``!system`` commands. These run on all input. Dynamic transformations, for things like unescaped magics and the exit autocall, depend on the state of the interpreter. These only apply to single line inputs. These string-based transformations are followed by AST transformations; see :meth:`transform_ast`. """ # Static input transformations cell = self.input_transformer_manager.transform_cell(raw_cell) if len(cell.splitlines()) == 1: # Dynamic transformations - only applied for single line commands with self.builtin_trap: # use prefilter_lines to handle trailing newlines # restore trailing newline for ast.parse cell = self.prefilter_manager.prefilter_lines(cell) + '\n' lines = cell.splitlines(keepends=True) for transform in self.input_transformers_post: lines = transform(lines) cell = ''.join(lines) return cell def transform_ast(self, node): """Apply the AST transformations from self.ast_transformers Parameters ---------- node : ast.Node The root node to be transformed. Typically called with the ast.Module produced by parsing user input. Returns ------- An ast.Node corresponding to the node it was called with. Note that it may also modify the passed object, so don't rely on references to the original AST. """ for transformer in self.ast_transformers: try: node = transformer.visit(node) except InputRejected: # User-supplied AST transformers can reject an input by raising # an InputRejected. Short-circuit in this case so that we # don't unregister the transform. raise except Exception: warn("AST transformer %r threw an error. It will be unregistered." % transformer) self.ast_transformers.remove(transformer) if self.ast_transformers: ast.fix_missing_locations(node) return node async def run_ast_nodes( self, nodelist: ListType[stmt], cell_name: str, interactivity="last_expr", compiler=compile, result=None, ): """Run a sequence of AST nodes. The execution mode depends on the interactivity parameter. Parameters ---------- nodelist : list A sequence of AST nodes to run. cell_name : str Will be passed to the compiler as the filename of the cell. Typically the value returned by ip.compile.cache(cell). interactivity : str 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', specifying which nodes should be run interactively (displaying output from expressions). 'last_expr' will run the last node interactively only if it is an expression (i.e. expressions in loops or other blocks are not displayed) 'last_expr_or_assign' will run the last expression or the last assignment. Other values for this parameter will raise a ValueError. compiler : callable A function with the same interface as the built-in compile(), to turn the AST nodes into code objects. Default is the built-in compile(). result : ExecutionResult, optional An object to store exceptions that occur during execution. Returns ------- True if an exception occurred while running code, False if it finished running. """ if not nodelist: return if interactivity == 'last_expr_or_assign': if isinstance(nodelist[-1], _assign_nodes): asg = nodelist[-1] if isinstance(asg, ast.Assign) and len(asg.targets) == 1: target = asg.targets[0] elif isinstance(asg, _single_targets_nodes): target = asg.target else: target = None if isinstance(target, ast.Name): nnode = ast.Expr(ast.Name(target.id, ast.Load())) ast.fix_missing_locations(nnode) nodelist.append(nnode) interactivity = 'last_expr' _async = False if interactivity == 'last_expr': if isinstance(nodelist[-1], ast.Expr): interactivity = "last" else: interactivity = "none" if interactivity == 'none': to_run_exec, to_run_interactive = nodelist, [] elif interactivity == 'last': to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] elif interactivity == 'all': to_run_exec, to_run_interactive = [], nodelist else: raise ValueError("Interactivity was %r" % interactivity) try: def compare(code): is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE return is_async # refactor that to just change the mod constructor. to_run = [] for node in to_run_exec: to_run.append((node, "exec")) for node in to_run_interactive: to_run.append((node, "single")) for node, mode in to_run: if mode == "exec": mod = Module([node], []) elif mode == "single": mod = ast.Interactive([node]) # type: ignore with compiler.extra_flags( getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0) if self.autoawait else 0x0 ): code = compiler(mod, cell_name, mode) asy = compare(code) if await self.run_code(code, result, async_=asy): return True # Flush softspace if softspace(sys.stdout, 0): print() except: # It's possible to have exceptions raised here, typically by # compilation of odd code (such as a naked 'return' outside a # function) that did parse but isn't valid. Typically the exception # is a SyntaxError, but it's safest just to catch anything and show # the user a traceback. # We do only one try/except outside the loop to minimize the impact # on runtime, and also because if any node in the node list is # broken, we should stop execution completely. if result: result.error_before_exec = sys.exc_info()[1] self.showtraceback() return True return False async def run_code(self, code_obj, result=None, *, async_=False): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. Parameters ---------- code_obj : code object A compiled code object, to be executed result : ExecutionResult, optional An object to store exceptions that occur during execution. async_ : Bool (Experimental) Attempt to run top-level asynchronous code in a default loop. Returns ------- False : successful execution. True : an error occurred. """ # special value to say that anything above is IPython and should be # hidden. __tracebackhide__ = "__ipython_bottom__" # Set our own excepthook in case the user code tries to call it # directly, so that the IPython crash handler doesn't get triggered old_excepthook, sys.excepthook = sys.excepthook, self.excepthook # we save the original sys.excepthook in the instance, in case config # code (such as magics) needs access to it. self.sys_excepthook = old_excepthook outflag = True # happens in more places, so it's easier as default try: try: if async_: await eval(code_obj, self.user_global_ns, self.user_ns) else: exec(code_obj, self.user_global_ns, self.user_ns) finally: # Reset our crash handler in place sys.excepthook = old_excepthook except SystemExit as e: if result is not None: result.error_in_exec = e self.showtraceback(exception_only=True) warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) except bdb.BdbQuit: etype, value, tb = sys.exc_info() if result is not None: result.error_in_exec = value # the BdbQuit stops here except self.custom_exceptions: etype, value, tb = sys.exc_info() if result is not None: result.error_in_exec = value self.CustomTB(etype, value, tb) except: if result is not None: result.error_in_exec = sys.exc_info()[1] self.showtraceback(running_compiled_code=True) else: outflag = False return outflag # For backwards compatibility runcode = run_code def check_complete(self, code: str) -> Tuple[str, str]: """Return whether a block of code is ready to execute, or should be continued Parameters ---------- code : string Python input code, which can be multiline. Returns ------- status : str One of 'complete', 'incomplete', or 'invalid' if source is not a prefix of valid code. indent : str When status is 'incomplete', this is some whitespace to insert on the next line of the prompt. """ status, nspaces = self.input_transformer_manager.check_complete(code) return status, ' ' * (nspaces or 0) #------------------------------------------------------------------------- # Things related to GUI support and pylab #------------------------------------------------------------------------- active_eventloop = None def enable_gui(self, gui=None): raise NotImplementedError('Implement enable_gui in a subclass') def enable_matplotlib(self, gui=None): """Enable interactive matplotlib and inline figure support. This takes the following steps: 1. select the appropriate eventloop and matplotlib backend 2. set up matplotlib for interactive use with that backend 3. configure formatters for inline figure display 4. enable the selected gui eventloop Parameters ---------- gui : optional, string If given, dictates the choice of matplotlib GUI backend to use (should be one of IPython's supported backends, 'qt', 'osx', 'tk', 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by matplotlib (as dictated by the matplotlib build-time options plus the user's matplotlibrc configuration file). Note that not all backends make sense in all contexts, for example a terminal ipython can't display figures inline. """ from matplotlib_inline.backend_inline import configure_inline_support from IPython.core import pylabtools as pt gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) if gui != 'inline': # If we have our first gui selection, store it if self.pylab_gui_select is None: self.pylab_gui_select = gui # Otherwise if they are different elif gui != self.pylab_gui_select: print('Warning: Cannot change to a different GUI toolkit: %s.' ' Using %s instead.' % (gui, self.pylab_gui_select)) gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) pt.activate_matplotlib(backend) configure_inline_support(self, backend) # Now we must activate the gui pylab wants to use, and fix %run to take # plot updates into account self.enable_gui(gui) self.magics_manager.registry['ExecutionMagics'].default_runner = \ pt.mpl_runner(self.safe_execfile) return gui, backend def enable_pylab(self, gui=None, import_all=True, welcome_message=False): """Activate pylab support at runtime. This turns on support for matplotlib, preloads into the interactive namespace all of numpy and pylab, and configures IPython to correctly interact with the GUI event loop. The GUI backend to be used can be optionally selected with the optional ``gui`` argument. This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. Parameters ---------- gui : optional, string If given, dictates the choice of matplotlib GUI backend to use (should be one of IPython's supported backends, 'qt', 'osx', 'tk', 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by matplotlib (as dictated by the matplotlib build-time options plus the user's matplotlibrc configuration file). Note that not all backends make sense in all contexts, for example a terminal ipython can't display figures inline. import_all : optional, bool, default: True Whether to do `from numpy import *` and `from pylab import *` in addition to module imports. welcome_message : deprecated This argument is ignored, no welcome message will be displayed. """ from IPython.core.pylabtools import import_pylab gui, backend = self.enable_matplotlib(gui) # We want to prevent the loading of pylab to pollute the user's # namespace as shown by the %who* magics, so we execute the activation # code in an empty namespace, and we update *both* user_ns and # user_ns_hidden with this information. ns = {} import_pylab(ns, import_all) # warn about clobbered names ignored = {"__builtins__"} both = set(ns).intersection(self.user_ns).difference(ignored) clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] self.user_ns.update(ns) self.user_ns_hidden.update(ns) return gui, backend, clobbered #------------------------------------------------------------------------- # Utilities #------------------------------------------------------------------------- def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): """Expand python variables in a string. The depth argument indicates how many frames above the caller should be walked to look for the local namespace where to expand variables. The global namespace for expansion is always the user's interactive namespace. """ ns = self.user_ns.copy() try: frame = sys._getframe(depth+1) except ValueError: # This is thrown if there aren't that many frames on the stack, # e.g. if a script called run_line_magic() directly. pass else: ns.update(frame.f_locals) try: # We have to use .vformat() here, because 'self' is a valid and common # name, and expanding **ns for .format() would make it collide with # the 'self' argument of the method. cmd = formatter.vformat(cmd, args=[], kwargs=ns) except Exception: # if formatter couldn't format, just let it go untransformed pass return cmd def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), but it registers the created filename internally so ipython cleans it up at exit time. Optional inputs: - data(None): if data is given, it gets written out to the temp file immediately, and the file is closed again.""" dir_path = Path(tempfile.mkdtemp(prefix=prefix)) self.tempdirs.append(dir_path) handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path)) os.close(handle) # On Windows, there can only be one open handle on a file file_path = Path(filename) self.tempfiles.append(file_path) if data: file_path.write_text(data, encoding="utf-8") return filename def ask_yes_no(self, prompt, default=None, interrupt=None): if self.quiet: return True return ask_yes_no(prompt,default,interrupt) def show_usage(self): """Show a usage message""" page.page(IPython.core.usage.interactive_usage) def extract_input_lines(self, range_str, raw=False): """Return as a string a set of input history slices. Parameters ---------- range_str : str The set of slices is given as a string, like "~5/6-~4/2 4:8 9", since this function is for use by magic functions which get their arguments as strings. The number before the / is the session number: ~n goes n back from the current session. If empty string is given, returns history of current session without the last input. raw : bool, optional By default, the processed input is used. If this is true, the raw input history is used instead. Notes ----- Slices can be described with two notations: * ``N:M`` -> standard python form, means including items N...(M-1). * ``N-M`` -> include items N..M (closed endpoint). """ lines = self.history_manager.get_range_by_str(range_str, raw=raw) text = "\n".join(x for _, _, x in lines) # Skip the last line, as it's probably the magic that called this if not range_str: if "\n" not in text: text = "" else: text = text[: text.rfind("\n")] return text def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): """Get a code string from history, file, url, or a string or macro. This is mainly used by magic functions. Parameters ---------- target : str A string specifying code to retrieve. This will be tried respectively as: ranges of input history (see %history for syntax), url, corresponding .py file, filename, or an expression evaluating to a string or Macro in the user namespace. If empty string is given, returns complete history of current session, without the last line. raw : bool If true (default), retrieve raw history. Has no effect on the other retrieval mechanisms. py_only : bool (default False) Only try to fetch python code, do not try alternative methods to decode file if unicode fails. Returns ------- A string of code. ValueError is raised if nothing is found, and TypeError if it evaluates to an object of another type. In each case, .args[0] is a printable message. """ code = self.extract_input_lines(target, raw=raw) # Grab history if code: return code try: if target.startswith(('http://', 'https://')): return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) except UnicodeDecodeError as e: if not py_only : # Deferred import from urllib.request import urlopen response = urlopen(target) return response.read().decode('latin1') raise ValueError(("'%s' seem to be unreadable.") % target) from e potential_target = [target] try : potential_target.insert(0,get_py_filename(target)) except IOError: pass for tgt in potential_target : if os.path.isfile(tgt): # Read file try : return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) except UnicodeDecodeError as e: if not py_only : with io_open(tgt,'r', encoding='latin1') as f : return f.read() raise ValueError(("'%s' seem to be unreadable.") % target) from e elif os.path.isdir(os.path.expanduser(tgt)): raise ValueError("'%s' is a directory, not a regular file." % target) if search_ns: # Inspect namespace to load object source object_info = self.object_inspect(target, detail_level=1) if object_info['found'] and object_info['source']: return object_info['source'] try: # User namespace codeobj = eval(target, self.user_ns) except Exception as e: raise ValueError(("'%s' was not found in history, as a file, url, " "nor in the user namespace.") % target) from e if isinstance(codeobj, str): return codeobj elif isinstance(codeobj, Macro): return codeobj.value raise TypeError("%s is neither a string nor a macro." % target, codeobj) def _atexit_once(self): """ At exist operation that need to be called at most once. Second call to this function per instance will do nothing. """ if not getattr(self, "_atexit_once_called", False): self._atexit_once_called = True # Clear all user namespaces to release all references cleanly. self.reset(new_session=False) # Close the history session (this stores the end time and line count) # this must be *before* the tempfile cleanup, in case of temporary # history db self.history_manager.end_session() self.history_manager = None #------------------------------------------------------------------------- # Things related to IPython exiting #------------------------------------------------------------------------- def atexit_operations(self): """This will be executed at the time of exit. Cleanup operations and saving of persistent data that is done unconditionally by IPython should be performed here. For things that may depend on startup flags or platform specifics (such as having readline or not), register a separate atexit function in the code that has the appropriate information, rather than trying to clutter """ self._atexit_once() # Cleanup all tempfiles and folders left around for tfile in self.tempfiles: try: tfile.unlink() self.tempfiles.remove(tfile) except FileNotFoundError: pass del self.tempfiles for tdir in self.tempdirs: try: tdir.rmdir() self.tempdirs.remove(tdir) except FileNotFoundError: pass del self.tempdirs # Restore user's cursor if hasattr(self, "editing_mode") and self.editing_mode == "vi": sys.stdout.write("\x1b[0 q") sys.stdout.flush() def cleanup(self): self.restore_sys_module_state() # Overridden in terminal subclass to change prompts def switch_doctest_mode(self, mode): pass The provided code snippet includes necessary dependencies for implementing the `format_display_data` function. Write a Python function `def format_display_data(obj, include=None, exclude=None)` to solve the following problem: Return a format data dict for an object. By default all format types will be computed. Parameters ---------- obj : object The Python object whose format data will be computed. Returns ------- format_dict : dict A dictionary of key/value pairs, one or each format that was generated for the object. The keys are the format types, which will usually be MIME type strings and the values and JSON'able data structure containing the raw data for the representation in that format. include : list or tuple, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list or tuple, optional A list of format type string (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument. Here is the function: def format_display_data(obj, include=None, exclude=None): """Return a format data dict for an object. By default all format types will be computed. Parameters ---------- obj : object The Python object whose format data will be computed. Returns ------- format_dict : dict A dictionary of key/value pairs, one or each format that was generated for the object. The keys are the format types, which will usually be MIME type strings and the values and JSON'able data structure containing the raw data for the representation in that format. include : list or tuple, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list or tuple, optional A list of format type string (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument. """ from .interactiveshell import InteractiveShell return InteractiveShell.instance().display_formatter.format( obj, include, exclude )
Return a format data dict for an object. By default all format types will be computed. Parameters ---------- obj : object The Python object whose format data will be computed. Returns ------- format_dict : dict A dictionary of key/value pairs, one or each format that was generated for the object. The keys are the format types, which will usually be MIME type strings and the values and JSON'able data structure containing the raw data for the representation in that format. include : list or tuple, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list or tuple, optional A list of format type string (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument.
176,758
import os import subprocess import sys from .error import TryNext import os del os class TryNext(IPythonCoreError): """Try next hook exception. Raise this in your hook function to indicate that the next hook handler should be used to handle the operation. """ The provided code snippet includes necessary dependencies for implementing the `editor` function. Write a Python function `def editor(self, filename, linenum=None, wait=True)` to solve the following problem: Open the default editor at the given filename and linenumber. This is IPython's default editor hook, you can use it as an example to write your own modified one. To set your own editor function as the new editor hook, call ip.set_hook('editor',yourfunc). Here is the function: def editor(self, filename, linenum=None, wait=True): """Open the default editor at the given filename and linenumber. This is IPython's default editor hook, you can use it as an example to write your own modified one. To set your own editor function as the new editor hook, call ip.set_hook('editor',yourfunc).""" # IPython configures a default editor at startup by reading $EDITOR from # the environment, and falling back on vi (unix) or notepad (win32). editor = self.editor # marker for at which line to open the file (for existing objects) if linenum is None or editor=='notepad': linemark = '' else: linemark = '+%d' % int(linenum) # Enclose in quotes if necessary and legal if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': editor = '"%s"' % editor # Call the actual editor proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename), shell=True) if wait and proc.wait() != 0: raise TryNext()
Open the default editor at the given filename and linenumber. This is IPython's default editor hook, you can use it as an example to write your own modified one. To set your own editor function as the new editor hook, call ip.set_hook('editor',yourfunc).
176,759
import os import subprocess import sys from .error import TryNext def synchronize_with_editor(self, filename, linenum, column): pass
null
176,760
import os import subprocess import sys from .error import TryNext class TryNext(IPythonCoreError): """Try next hook exception. Raise this in your hook function to indicate that the next hook handler should be used to handle the operation. """ The provided code snippet includes necessary dependencies for implementing the `show_in_pager` function. Write a Python function `def show_in_pager(self, data, start, screen_lines)` to solve the following problem: Run a string through pager Here is the function: def show_in_pager(self, data, start, screen_lines): """ Run a string through pager """ # raising TryNext here will use the default paging functionality raise TryNext
Run a string through pager
176,761
import os import subprocess import sys from .error import TryNext The provided code snippet includes necessary dependencies for implementing the `pre_prompt_hook` function. Write a Python function `def pre_prompt_hook(self)` to solve the following problem: Run before displaying the next prompt Use this e.g. to display output from asynchronous operations (in order to not mess up text entry) Here is the function: def pre_prompt_hook(self): """ Run before displaying the next prompt Use this e.g. to display output from asynchronous operations (in order to not mess up text entry) """ return None
Run before displaying the next prompt Use this e.g. to display output from asynchronous operations (in order to not mess up text entry)
176,762
import os import subprocess import sys from .error import TryNext class CommandChainDispatcher: """ Dispatch calls to a chain of commands until some func can handle it Usage: instantiate, execute "add" to add commands (with optional priority), execute normally via f() calling mechanism. """ def __init__(self,commands=None): if commands is None: self.chain = [] else: self.chain = commands def __call__(self,*args, **kw): """ Command chain is called just like normal func. This will call all funcs in chain with the same args as were given to this function, and return the result of first func that didn't raise TryNext""" last_exc = TryNext() for prio,cmd in self.chain: #print "prio",prio,"cmd",cmd #dbg try: return cmd(*args, **kw) except TryNext as exc: last_exc = exc # if no function will accept it, raise TryNext up to the caller raise last_exc def __str__(self): return str(self.chain) def add(self, func, priority=0): """ Add a func to the cmd chain with given priority """ self.chain.append((priority, func)) self.chain.sort(key=lambda x: x[0]) def __iter__(self): """ Return all objects in chain. Handy if the objects are not callable. """ return iter(self.chain) import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False def win32_clipboard_get(): """ Get the current clipboard's text on Windows. Requires Mark Hammond's pywin32 extensions. """ try: import win32clipboard except ImportError as e: raise TryNext("Getting text from the clipboard requires the pywin32 " "extensions: http://sourceforge.net/projects/pywin32/") from e win32clipboard.OpenClipboard() try: text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) except (TypeError, win32clipboard.error): try: text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) except (TypeError, win32clipboard.error) as e: raise ClipboardEmpty from e finally: win32clipboard.CloseClipboard() return text def osx_clipboard_get() -> str: """ Get the clipboard's text on OS X. """ p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], stdout=subprocess.PIPE) bytes_, stderr = p.communicate() # Text comes in with old Mac \r line endings. Change them to \n. bytes_ = bytes_.replace(b'\r', b'\n') text = py3compat.decode(bytes_) return text def tkinter_clipboard_get(): """ Get the clipboard's text using Tkinter. This is the default on systems that are not Windows or OS X. It may interfere with other UI toolkits and should be replaced with an implementation that uses that toolkit. """ try: from tkinter import Tk, TclError 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 as e: raise ClipboardEmpty from e finally: root.destroy() text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) return text def wayland_clipboard_get(): """Get the clipboard's text under Wayland using wl-paste command. This requires Wayland and wl-clipboard installed and running. """ if os.environ.get("XDG_SESSION_TYPE") != "wayland": raise TryNext("wayland is not detected") try: with subprocess.Popen(["wl-paste"], stdout=subprocess.PIPE) as p: raw, err = p.communicate() if p.wait(): raise TryNext(err) except FileNotFoundError as e: raise TryNext( "Getting text from the clipboard under Wayland requires the wl-clipboard " "extension: https://github.com/bugaevc/wl-clipboard" ) from e if not raw: raise ClipboardEmpty try: text = py3compat.decode(raw) except UnicodeDecodeError as e: raise ClipboardEmpty from e return text The provided code snippet includes necessary dependencies for implementing the `clipboard_get` function. Write a Python function `def clipboard_get(self)` to solve the following problem: Get text from the clipboard. Here is the function: def clipboard_get(self): """ Get text from the clipboard. """ from ..lib.clipboard import ( osx_clipboard_get, tkinter_clipboard_get, win32_clipboard_get, wayland_clipboard_get, ) if sys.platform == 'win32': chain = [win32_clipboard_get, tkinter_clipboard_get] elif sys.platform == 'darwin': chain = [osx_clipboard_get, tkinter_clipboard_get] else: chain = [wayland_clipboard_get, tkinter_clipboard_get] dispatcher = CommandChainDispatcher() for func in chain: dispatcher.add(func) text = dispatcher() return text
Get text from the clipboard.
176,763
from warnings import warn import ast import codeop import io import re import sys import tokenize import warnings from typing import List from IPython.core.inputtransformer import (leading_indent, classic_prompt, ipy_prompt, cellmagic, assemble_logical_lines, help_end, escaped_commands, assign_from_magic, assign_from_system, assemble_python_lines, ) from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') The provided code snippet includes necessary dependencies for implementing the `num_ini_spaces` function. Write a Python function `def num_ini_spaces(s)` to solve the following problem: Return the number of initial spaces in a string. Note that tabs are counted as a single space. For now, we do *not* support mixing of tabs and spaces in the user's input. Parameters ---------- s : string Returns ------- n : int Here is the function: def num_ini_spaces(s): """Return the number of initial spaces in a string. Note that tabs are counted as a single space. For now, we do *not* support mixing of tabs and spaces in the user's input. Parameters ---------- s : string Returns ------- n : int """ ini_spaces = ini_spaces_re.match(s) if ini_spaces: return ini_spaces.end() else: return 0
Return the number of initial spaces in a string. Note that tabs are counted as a single space. For now, we do *not* support mixing of tabs and spaces in the user's input. Parameters ---------- s : string Returns ------- n : int
176,764
from warnings import warn import ast import codeop import io import re import sys import tokenize import warnings from typing import List from IPython.core.inputtransformer import (leading_indent, classic_prompt, ipy_prompt, cellmagic, assemble_logical_lines, help_end, escaped_commands, assign_from_magic, assign_from_system, assemble_python_lines, ) from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) INCOMPLETE_STRING = tokenize.N_TOKENS IN_MULTILINE_STATEMENT = tokenize.N_TOKENS + 1 def partial_tokens(s): """Iterate over tokens from a possibly-incomplete string of code. This adds two special token types: INCOMPLETE_STRING and IN_MULTILINE_STATEMENT. These can only occur as the last token yielded, and represent the two main ways for code to be incomplete. """ readline = io.StringIO(s).readline token = tokenize.TokenInfo(tokenize.NEWLINE, '', (1, 0), (1, 0), '') try: for token in tokenize.generate_tokens(readline): yield token except tokenize.TokenError as e: # catch EOF error lines = s.splitlines(keepends=True) end = len(lines), len(lines[-1]) if 'multi-line string' in e.args[0]: l, c = start = token.end s = lines[l-1][c:] + ''.join(lines[l:]) yield IncompleteString(s, start, end, lines[-1]) elif 'multi-line statement' in e.args[0]: yield InMultilineStatement(end, lines[-1]) else: raise The provided code snippet includes necessary dependencies for implementing the `find_next_indent` function. Write a Python function `def find_next_indent(code)` to solve the following problem: Find the number of spaces for the next line of indentation Here is the function: def find_next_indent(code): """Find the number of spaces for the next line of indentation""" tokens = list(partial_tokens(code)) if tokens[-1].type == tokenize.ENDMARKER: tokens.pop() if not tokens: return 0 while (tokens[-1].type in {tokenize.DEDENT, tokenize.NEWLINE, tokenize.COMMENT}): tokens.pop() if tokens[-1].type == INCOMPLETE_STRING: # Inside a multiline string return 0 # Find the indents used before prev_indents = [0] def _add_indent(n): if n != prev_indents[-1]: prev_indents.append(n) tokiter = iter(tokens) for tok in tokiter: if tok.type in {tokenize.INDENT, tokenize.DEDENT}: _add_indent(tok.end[1]) elif (tok.type == tokenize.NL): try: _add_indent(next(tokiter).start[1]) except StopIteration: break last_indent = prev_indents.pop() # If we've just opened a multiline statement (e.g. 'a = ['), indent more if tokens[-1].type == IN_MULTILINE_STATEMENT: if tokens[-2].exact_type in {tokenize.LPAR, tokenize.LSQB, tokenize.LBRACE}: return last_indent + 4 return last_indent if tokens[-1].exact_type == tokenize.COLON: # Line ends with colon - indent return last_indent + 4 if last_indent: # Examine the last line for dedent cues - statements like return or # raise which normally end a block of code. last_line_starts = 0 for i, tok in enumerate(tokens): if tok.type == tokenize.NEWLINE: last_line_starts = i + 1 last_line_tokens = tokens[last_line_starts:] names = [t.string for t in last_line_tokens if t.type == tokenize.NAME] if names and names[0] in {'raise', 'return', 'pass', 'break', 'continue'}: # Find the most recent indentation less than the current level for indent in reversed(prev_indents): if indent < last_indent: return indent return last_indent
Find the number of spaces for the next line of indentation
176,765
from warnings import warn import ast import codeop import io import re import sys import tokenize import warnings from typing import List from IPython.core.inputtransformer import (leading_indent, classic_prompt, ipy_prompt, cellmagic, assemble_logical_lines, help_end, escaped_commands, assign_from_magic, assign_from_system, assemble_python_lines, ) from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) The provided code snippet includes necessary dependencies for implementing the `last_blank` function. Write a Python function `def last_blank(src)` to solve the following problem: Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. Here is the function: def last_blank(src): """Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False ll = src.splitlines()[-1] return (ll == '') or ll.isspace()
Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
176,766
from warnings import warn import ast import codeop import io import re import sys import tokenize import warnings from typing import List from IPython.core.inputtransformer import (leading_indent, classic_prompt, ipy_prompt, cellmagic, assemble_logical_lines, help_end, escaped_commands, assign_from_magic, assign_from_system, assemble_python_lines, ) from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE) last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE) The provided code snippet includes necessary dependencies for implementing the `last_two_blanks` function. Write a Python function `def last_two_blanks(src)` to solve the following problem: Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. Here is the function: def last_two_blanks(src): """Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False # The logic here is tricky: I couldn't get a regexp to work and pass all # the tests, so I took a different approach: split the source by lines, # grab the last two and prepend '###\n' as a stand-in for whatever was in # the body before the last two lines. Then, with that structure, it's # possible to analyze with two regexps. Not the most elegant solution, but # it works. If anyone tries to change this logic, make sure to validate # the whole test suite first! new_src = '\n'.join(['###\n'] + src.splitlines()[-2:]) return (bool(last_two_blanks_re.match(new_src)) or bool(last_two_blanks_re2.match(new_src)) )
Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
176,767
from warnings import warn import ast import codeop import io import re import sys import tokenize import warnings from typing import List from IPython.core.inputtransformer import (leading_indent, classic_prompt, ipy_prompt, cellmagic, assemble_logical_lines, help_end, escaped_commands, assign_from_magic, assign_from_system, assemble_python_lines, ) from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) The provided code snippet includes necessary dependencies for implementing the `remove_comments` function. Write a Python function `def remove_comments(src)` to solve the following problem: Remove all comments from input source. Note: comments are NOT recognized inside of strings! Parameters ---------- src : string A single or multiline input string. Returns ------- String with all Python comments removed. Here is the function: def remove_comments(src): """Remove all comments from input source. Note: comments are NOT recognized inside of strings! Parameters ---------- src : string A single or multiline input string. Returns ------- String with all Python comments removed. """ return re.sub('#.*', '', src)
Remove all comments from input source. Note: comments are NOT recognized inside of strings! Parameters ---------- src : string A single or multiline input string. Returns ------- String with all Python comments removed.
176,768
from warnings import warn import ast import codeop import io import re import sys import tokenize import warnings from typing import List from IPython.core.inputtransformer import (leading_indent, classic_prompt, ipy_prompt, cellmagic, assemble_logical_lines, help_end, escaped_commands, assign_from_magic, assign_from_system, assemble_python_lines, ) from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False The provided code snippet includes necessary dependencies for implementing the `get_input_encoding` function. Write a Python function `def get_input_encoding()` to solve the following problem: Return the default standard input encoding. If sys.stdin has no encoding, 'ascii' is returned. Here is the function: def get_input_encoding(): """Return the default standard input encoding. If sys.stdin has no encoding, 'ascii' is returned.""" # There are strange environments for which sys.stdin.encoding is None. We # ensure that a valid encoding is returned. encoding = getattr(sys.stdin, 'encoding', None) if encoding is None: encoding = 'ascii' return encoding
Return the default standard input encoding. If sys.stdin has no encoding, 'ascii' is returned.
176,769
from typing import ( Any, Callable, Dict, Set, Sequence, Tuple, NamedTuple, Type, Literal, Union, TYPE_CHECKING, ) import ast import builtins import collections import operator import sys from functools import cached_property from dataclasses import dataclass, field from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.decorators import undoc class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) Union: _SpecialForm = ... The provided code snippet includes necessary dependencies for implementing the `_unbind_method` function. Write a Python function `def _unbind_method(func: Callable) -> Union[Callable, None]` to solve the following problem: Get unbound method for given bound method. Returns None if cannot get unbound method, or method is already unbound. Here is the function: def _unbind_method(func: Callable) -> Union[Callable, None]: """Get unbound method for given bound method. Returns None if cannot get unbound method, or method is already unbound. """ owner = getattr(func, "__self__", None) owner_class = type(owner) name = getattr(func, "__name__", None) instance_dict_overrides = getattr(owner, "__dict__", None) if ( owner is not None and name and ( not instance_dict_overrides or (instance_dict_overrides and name not in instance_dict_overrides) ) ): return getattr(owner_class, name) return None
Get unbound method for given bound method. Returns None if cannot get unbound method, or method is already unbound.
176,770
from typing import ( Any, Callable, Dict, Set, Sequence, Tuple, NamedTuple, Type, Literal, Union, TYPE_CHECKING, ) import ast import builtins import collections import operator import sys from functools import cached_property from dataclasses import dataclass, field from IPython.utils.docs import GENERATING_DOCUMENTATION from IPython.utils.decorators import undoc def _has_original_dunder_external( value, module_name: str, access_path: Sequence[str], method_name: str, ): def _has_original_dunder( value, allowed_types, allowed_methods, allowed_external, method_name ): # note: Python ignores `__getattr__`/`__getitem__` on instances, # we only need to check at class level value_type = type(value) # strict type check passes → no need to check method if value_type in allowed_types: return True method = getattr(value_type, method_name, None) if method is None: return None if method in allowed_methods: return True for module_name, *access_path in allowed_external: if _has_original_dunder_external(value, module_name, access_path, method_name): return True return False
null