Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/IPython/core/__init__.pyAdded
- lib/python3.12/site-packages/IPython/core/alias.pyAdded+268
- lib/python3.12/site-packages/IPython/core/application.pyAdded+492
- lib/python3.12/site-packages/IPython/core/async_helpers.pyAdded+150
- lib/python3.12/site-packages/IPython/core/autocall.pyAdded+70
- lib/python3.12/site-packages/IPython/core/builtin_trap.pyAdded+93
- lib/python3.12/site-packages/IPython/core/completer.pyAdded
- lib/python3.12/site-packages/IPython/core/debugger.pyAdded+1376
- lib/python3.12/site-packages/IPython/core/debugger_backport.pyAdded+206
- lib/python3.12/site-packages/IPython/core/display.pyAdded+1266
- lib/python3.12/site-packages/IPython/core/display_functions.pyAdded+371
- lib/python3.12/site-packages/IPython/core/display_trap.pyAdded+74
- lib/python3.12/site-packages/IPython/core/displayhook.pyAdded+346
- lib/python3.12/site-packages/IPython/core/doctb.pyAdded+445
- lib/python3.12/site-packages/IPython/core/events.pyAdded+172
- lib/python3.12/site-packages/IPython/core/formatters.pyAdded+1090
- lib/python3.12/site-packages/IPython/core/historyapp.pyAdded+158
- lib/python3.12/site-packages/IPython/core/inputtransformer2.pyAdded+898
- lib/python3.12/site-packages/IPython/core/interactiveshell.pyAdded
- lib/python3.12/site-packages/IPython/core/macro.pyAdded+53
- lib/python3.12/site-packages/IPython/core/magic_arguments.pyAdded+312
- lib/python3.12/site-packages/IPython/core/oinspect.pyAdded+1215
- lib/python3.12/site-packages/IPython/core/page.pyAdded+348
- lib/python3.12/site-packages/IPython/core/payload.pyAdded+54
- lib/python3.12/site-packages/IPython/core/payloadpage.pyAdded+41
- lib/python3.12/site-packages/IPython/core/prefilter.pyAdded+707
- lib/python3.12/site-packages/IPython/core/profileapp.pyAdded+315
- lib/python3.12/site-packages/IPython/core/profiledir.pyAdded+244
- lib/python3.12/site-packages/IPython/core/pylabtools.pyAdded+514
- lib/python3.12/site-packages/IPython/core/shellapp.pyAdded+500
- lib/python3.12/site-packages/IPython/core/splitinput.pyAdded+155
- lib/python3.12/site-packages/IPython/core/tips.pyAdded+128
- lib/python3.12/site-packages/IPython/core/ultratb.pyAdded+1263
- lib/python3.12/site-packages/IPython/core/usage.pyAdded+341
- lib/python3.12/site-packages/IPython/lib/__init__.pyAdded+11
- lib/python3.12/site-packages/IPython/lib/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/backgroundjobs.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/clipboard.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/deepreload.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/demo.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/display.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/editorhooks.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/guisupport.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/latextools.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/lexers.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/__pycache__/pretty.cpython-312.pycAdded
- lib/python3.12/site-packages/IPython/lib/backgroundjobs.pyAdded+491
- lib/python3.12/site-packages/IPython/lib/clipboard.pyAdded+102
- lib/python3.12/site-packages/IPython/lib/deepreload.pyAdded+310
- lib/python3.12/site-packages/IPython/lib/demo.pyAdded+672
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268# encoding: utf-8"""System command aliases.
Authors:
* Fernando Perez* Brian Granger"""
#-----------------------------------------------------------------------------# Copyright (C) 2008-2011 The IPython Development Team## Distributed under the terms of the BSD License.## The full license is in the file COPYING.txt, distributed with this software.#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------
import osimport reimport sys
from traitlets.config.configurable import Configurablefrom .error import UsageError
from traitlets import List, Instancefrom logging import error
import typing as t
#-----------------------------------------------------------------------------# Utilities#-----------------------------------------------------------------------------
# This is used as the pattern for calls to split_user_input.shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
def default_aliases() -> t.List[t.Tuple[str, str]]: """Return list of shell aliases to auto-define. """ # Note: the aliases defined here should be safe to use on a kernel # regardless of what frontend it is attached to. Frontends that use a # kernel in-process can define additional aliases that will only work in # their case. For example, things like 'less' or 'clear' that manipulate # the terminal should NOT be declared here, as they will only work if the # kernel is running inside a true terminal, and not over the network.
if os.name == 'posix': default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('mv', 'mv'), ('rm', 'rm'), ('cp', 'cp'), ('cat', 'cat'), ] # Useful set of ls aliases. The GNU and BSD options are a little # different, so we make aliases that provide as similar as possible # behavior in ipython, by passing the right flags for each platform if sys.platform.startswith('linux'): ls_aliases = [('ls', 'ls -F --color'), # long ls ('ll', 'ls -F -o --color'), # ls normal files only ('lf', 'ls -F -o --color %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -o --color %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -o --color %l | grep /$'), # things which are executable ('lx', 'ls -F -o --color %l | grep ^-..x'), ] elif sys.platform.startswith('openbsd') or sys.platform.startswith('netbsd'): # OpenBSD, NetBSD. The ls implementation on these platforms do not support # the -G switch and lack the ability to use colorized output. ls_aliases = [('ls', 'ls -F'), # long ls ('ll', 'ls -F -l'), # ls normal files only ('lf', 'ls -F -l %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -l %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -l %l | grep /$'), # things which are executable ('lx', 'ls -F -l %l | grep ^-..x'), ] else: # BSD, OSX, etc. ls_aliases = [('ls', 'ls -F -G'), # long ls ('ll', 'ls -F -l -G'), # ls normal files only ('lf', 'ls -F -l -G %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -l -G %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -G -l %l | grep /$'), # things which are executable ('lx', 'ls -F -l -G %l | grep ^-..x'), ] default_aliases = default_aliases + ls_aliases elif os.name in ['nt', 'dos']: default_aliases = [('ls', 'dir /on'), ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'), ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'), ] else: default_aliases = []
return default_aliases
class AliasError(Exception): pass
class InvalidAliasError(AliasError): pass
class Alias: """Callable object storing the details of one alias.
Instances are registered as magic functions to allow use of aliases. """
# Prepare blacklist blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
def __init__(self, shell, name, cmd): self.shell = shell self.name = name self.cmd = cmd self.__doc__ = "Alias for `!{}`".format(cmd) self.nargs = self.validate()
def validate(self): """Validate the alias, and return the number of arguments.""" if self.name in self.blacklist: raise InvalidAliasError("The name %s can't be aliased " "because it is a keyword or builtin." % self.name) try: caller = self.shell.magics_manager.magics['line'][self.name] except KeyError: pass else: if not isinstance(caller, Alias): raise InvalidAliasError("The name %s can't be aliased " "because it is another magic command." % self.name)
if not (isinstance(self.cmd, str)): raise InvalidAliasError("An alias command must be a string, " "got: %r" % self.cmd)
nargs = self.cmd.count('%s') - self.cmd.count('%%s') if (nargs > 0) and (self.cmd.find('%l') >= 0): raise InvalidAliasError('The %s and %l specifiers are mutually ' 'exclusive in alias definitions.')
return nargs
def __repr__(self): return "<alias {} for {!r}>".format(self.name, self.cmd)
def __call__(self, rest=''): cmd = self.cmd nargs = self.nargs # Expand the %l special to be the user's input line if cmd.find('%l') >= 0: cmd = cmd.replace('%l', rest) rest = '' if nargs==0: if cmd.find('%%s') >= 1: cmd = cmd.replace('%%s', '%s') # Simple, argument-less aliases cmd = '%s %s' % (cmd, rest) else: # Handle aliases with positional arguments args = rest.split(None, nargs) if len(args) < nargs: raise UsageError('Alias <%s> requires %s arguments, %s given.' % (self.name, nargs, len(args))) cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
self.shell.system(cmd)
#-----------------------------------------------------------------------------# Main AliasManager class#-----------------------------------------------------------------------------
class AliasManager(Configurable): default_aliases: List = List(default_aliases()).tag(config=True) user_aliases: List = List(default_value=[]).tag(config=True) shell = Instance( "IPython.core.interactiveshell.InteractiveShellABC", allow_none=True )
def __init__(self, shell=None, **kwargs): super(AliasManager, self).__init__(shell=shell, **kwargs) # For convenient access if self.shell is not None: self.linemagics = self.shell.magics_manager.magics["line"] self.init_aliases()
def init_aliases(self): # Load default & user aliases for name, cmd in self.default_aliases + self.user_aliases: if ( cmd.startswith("ls ") and self.shell is not None and self.shell.colors == "nocolor" ): cmd = cmd.replace(" --color", "") self.soft_define_alias(name, cmd)
@property def aliases(self): return [(n, func.cmd) for (n, func) in self.linemagics.items() if isinstance(func, Alias)]
def soft_define_alias(self, name, cmd): """Define an alias, but don't raise on an AliasError.""" try: self.define_alias(name, cmd) except AliasError as e: error("Invalid alias: %s" % e)
def define_alias(self, name, cmd): """Define a new alias after validating it.
This will raise an :exc:`AliasError` if there are validation problems. """ caller = Alias(shell=self.shell, name=name, cmd=cmd) self.shell.magics_manager.register_function(caller, magic_kind='line', magic_name=name)
def get_alias(self, name): """Return an alias, or None if no alias by that name exists.""" aname = self.linemagics.get(name, None) return aname if isinstance(aname, Alias) else None
def is_alias(self, name): """Return whether or not a given name has been defined as an alias""" return self.get_alias(name) is not None
def undefine_alias(self, name): if self.is_alias(name): del self.linemagics[name] else: raise ValueError('%s is not an alias' % name)
def clear_aliases(self): for name, _ in self.aliases: self.undefine_alias(name)
def retrieve_alias(self, name): """Retrieve the command to which an alias expands.""" caller = self.get_alias(name) if caller: return caller.cmd else: raise ValueError('%s is not an alias' % name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492# encoding: utf-8"""An application for IPython.
All top-level applications should use the classes in this module forhandling configuration and creating configurables.
The job of an :class:`Application` is to create the master configurationobject and then create the configurable objects, passing the config to them."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import atexitfrom copy import deepcopyimport loggingimport osimport shutilimport sys
from pathlib import Path
from traitlets.config.application import Application, catch_config_errorfrom traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoaderfrom IPython.core import release, crashhandlerfrom IPython.core.profiledir import ProfileDir, ProfileDirErrorfrom IPython.paths import get_ipython_dir, get_ipython_package_dirfrom IPython.utils.path import ensure_dir_existsfrom traitlets import ( List, Unicode, Type, Bool, Set, Instance, Undefined, default, observe,)
if os.name == "nt": programdata = os.environ.get("PROGRAMDATA", None) if programdata is not None: SYSTEM_CONFIG_DIRS = [str(Path(programdata) / "ipython")] else: # PROGRAMDATA is not defined by default on XP. SYSTEM_CONFIG_DIRS = []else: SYSTEM_CONFIG_DIRS = [ "/usr/local/etc/ipython", "/etc/ipython", ]
ENV_CONFIG_DIRS = []_env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython')if _env_config_dir not in SYSTEM_CONFIG_DIRS: # only add ENV_CONFIG if sys.prefix is not already included ENV_CONFIG_DIRS.append(_env_config_dir)
_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')if _envvar in {None, ''}: IPYTHON_SUPPRESS_CONFIG_ERRORS = Noneelse: if _envvar.lower() in {'1','true'}: IPYTHON_SUPPRESS_CONFIG_ERRORS = True elif _envvar.lower() in {'0','false'} : IPYTHON_SUPPRESS_CONFIG_ERRORS = False else: sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
# aliases and flags
base_aliases = {}if isinstance(Application.aliases, dict): # traitlets 5 base_aliases.update(Application.aliases)base_aliases.update( { "profile-dir": "ProfileDir.location", "profile": "BaseIPythonApplication.profile", "ipython-dir": "BaseIPythonApplication.ipython_dir", "log-level": "Application.log_level", "config": "BaseIPythonApplication.extra_config_file", })
base_flags = dict()if isinstance(Application.flags, dict): # traitlets 5 base_flags.update(Application.flags)base_flags.update( dict( debug=( {"Application": {"log_level": logging.DEBUG}}, "set log level to logging.DEBUG (maximize logging output)", ), quiet=( {"Application": {"log_level": logging.CRITICAL}}, "set log level to logging.CRITICAL (minimize logging output)", ), init=( { "BaseIPythonApplication": { "copy_config_files": True, "auto_create": True, } }, """Initialize profile with default config files. This is equivalent to running `ipython profile create <profile>` prior to startup. """, ), ))
class ProfileAwareConfigLoader(PyFileConfigLoader): """A Python file config loader that is aware of IPython profiles.""" def load_subconfig(self, fname, path=None, profile=None): if profile is not None: try: profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile, ) except ProfileDirError: return path = profile_dir.location return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
class BaseIPythonApplication(Application): name = "ipython" description = "IPython: an enhanced interactive Python shell." version = Unicode(release.version)
aliases = base_aliases flags = base_flags classes = List([ProfileDir]) # enable `load_subconfig('cfg.py', profile='name')` python_config_loader_class = ProfileAwareConfigLoader
# Track whether the config_file has changed, # because some logic happens only if we aren't using the default. config_file_specified = Set()
config_file_name = Unicode() @default('config_file_name') def _config_file_name_default(self): return self.name.replace('-','_') + u'_config.py' @observe('config_file_name') def _config_file_name_changed(self, change): if change['new'] != change['old']: self.config_file_specified.add(change['new'])
# The directory that contains IPython's builtin profiles. builtin_profile_dir = Unicode( os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default') ) config_file_paths = List(Unicode()) @default('config_file_paths') def _config_file_paths_default(self): return []
extra_config_file = Unicode( help="""Path to an extra config file to load. If specified, load this config file in addition to any other IPython config. """).tag(config=True) @observe('extra_config_file') def _extra_config_file_changed(self, change): old = change['old'] new = change['new'] try: self.config_files.remove(old) except ValueError: pass self.config_file_specified.add(new) self.config_files.append(new)
profile = Unicode(u'default', help="""The IPython profile to use.""" ).tag(config=True) @observe('profile') def _profile_changed(self, change): self.builtin_profile_dir = os.path.join( get_ipython_package_dir(), u'config', u'profile', change['new'] )
add_ipython_dir_to_sys_path = Bool( False, """Should the IPython profile directory be added to sys path ?
This option was non-existing before IPython 8.0, and ipython_dir was added to sys path to allow import of extensions present there. This was historical baggage from when pip did not exist. This now default to false, but can be set to true for legacy reasons. """, ).tag(config=True)
ipython_dir = Unicode( help=""" The name of the IPython directory. This directory is used for logging configuration (through profiles), history storage, etc. The default is usually $HOME/.ipython. This option can also be specified through the environment variable IPYTHONDIR. """ ).tag(config=True) @default('ipython_dir') def _ipython_dir_default(self): d = get_ipython_dir() self._ipython_dir_changed({ 'name': 'ipython_dir', 'old': d, 'new': d, }) return d _in_init_profile_dir = False
profile_dir = Instance(ProfileDir, allow_none=True)
@default('profile_dir') def _profile_dir_default(self): # avoid recursion if self._in_init_profile_dir: return # profile_dir requested early, force initialization self.init_profile_dir() return self.profile_dir
overwrite = Bool(False, help="""Whether to overwrite existing config files when copying""" ).tag(config=True)
auto_create = Bool(False, help="""Whether to create profile dir if it doesn't exist""" ).tag(config=True)
config_files = List(Unicode())
@default('config_files') def _config_files_default(self): return [self.config_file_name]
copy_config_files = Bool(False, help="""Whether to install the default config files into the profile dir. If a new profile is being created, and IPython contains config files for that profile, then they will be staged into the new directory. Otherwise, default config files will be automatically generated. """).tag(config=True) verbose_crash = Bool(False, help="""Create a massive crash report when IPython encounters what may be an internal error. The default is to append a short message to the usual traceback""").tag(config=True)
# The class to use as the crash handler. crash_handler_class = Type(crashhandler.CrashHandler)
@catch_config_error def __init__(self, **kwargs): super(BaseIPythonApplication, self).__init__(**kwargs) # ensure current working directory exists try: os.getcwd() except: # exit if cwd doesn't exist self.log.error("Current working directory doesn't exist.") self.exit(1)
#------------------------------------------------------------------------- # Various stages of Application creation #------------------------------------------------------------------------- def init_crash_handler(self): """Create a crash handler, typically setting sys.excepthook to it.""" self.crash_handler = self.crash_handler_class(self) sys.excepthook = self.excepthook def unset_crashhandler(): sys.excepthook = sys.__excepthook__ atexit.register(unset_crashhandler) def excepthook(self, etype, evalue, tb): """this is sys.excepthook after init_crashhandler
set self.verbose_crash=True to use our full crashhandler, instead of a regular traceback with a short message (crash_handler_lite) """ if self.verbose_crash: return self.crash_handler(etype, evalue, tb) else: return crashhandler.crash_handler_lite(etype, evalue, tb)
@observe('ipython_dir') def _ipython_dir_changed(self, change): old = change['old'] new = change['new'] if old is not Undefined: str_old = os.path.abspath(old) if str_old in sys.path: sys.path.remove(str_old) if self.add_ipython_dir_to_sys_path: str_path = os.path.abspath(new) sys.path.append(str_path) ensure_dir_exists(new) readme = os.path.join(new, "README") readme_src = os.path.join( get_ipython_package_dir(), "config", "profile", "README" ) if not os.path.exists(readme) and os.path.exists(readme_src): shutil.copy(readme_src, readme) for d in ("extensions", "nbextensions"): path = os.path.join(new, d) try: ensure_dir_exists(path) except OSError as e: # this will not be EEXIST self.log.error("couldn't create path %s: %s", path, e) self.log.debug("IPYTHONDIR set to: %s", new)
def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS): """Load the config file.
By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail.
`suppress_errors` default value is to be `None` in which case the behavior default to the one of `traitlets.Application`.
The default value can be set : - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive). - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive). - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
Any other value are invalid, and will make IPython exit with a non-zero return code. """
self.log.debug("Searching path %s for config files", self.config_file_paths) base_config = 'ipython_config.py' self.log.debug("Attempting to load config file: %s" % base_config) try: if suppress_errors is not None: old_value = Application.raise_config_file_errors Application.raise_config_file_errors = not suppress_errors Application.load_config_file( self, base_config, path=self.config_file_paths ) except ConfigFileNotFound: # ignore errors loading parent self.log.debug("Config file %s not found", base_config) pass if suppress_errors is not None: Application.raise_config_file_errors = old_value for config_file_name in self.config_files: if not config_file_name or config_file_name == base_config: continue self.log.debug("Attempting to load config file: %s" % self.config_file_name) try: Application.load_config_file( self, config_file_name, path=self.config_file_paths ) except ConfigFileNotFound: # Only warn if the default config file was NOT being used. if config_file_name in self.config_file_specified: msg = self.log.warning else: msg = self.log.debug msg("Config file not found, skipping: %s", config_file_name) except Exception: # For testing purposes. if not suppress_errors: raise self.log.warning("Error loading config file: %s" % self.config_file_name, exc_info=True)
def init_profile_dir(self): """initialize the profile dir""" self._in_init_profile_dir = True if self.profile_dir is not None: # already ran return if 'ProfileDir.location' not in self.config: # location not specified, find by profile name try: p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config) except ProfileDirError: # not found, maybe create it (always create default profile) if self.auto_create or self.profile == 'default': try: p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config) except ProfileDirError: self.log.fatal("Could not create profile: %r"%self.profile) self.exit(1) else: self.log.info("Created profile dir: %r"%p.location) else: self.log.fatal("Profile %r not found."%self.profile) self.exit(1) else: self.log.debug("Using existing profile dir: %r", p.location) else: location = self.config.ProfileDir.location # location is fully specified try: p = ProfileDir.find_profile_dir(location, self.config) except ProfileDirError: # not found, maybe create it if self.auto_create: try: p = ProfileDir.create_profile_dir(location, self.config) except ProfileDirError: self.log.fatal("Could not create profile directory: %r"%location) self.exit(1) else: self.log.debug("Creating new profile dir: %r"%location) else: self.log.fatal("Profile directory %r not found."%location) self.exit(1) else: self.log.debug("Using existing profile dir: %r", p.location) # if profile_dir is specified explicitly, set profile name dir_name = os.path.basename(p.location) if dir_name.startswith('profile_'): self.profile = dir_name[8:]
self.profile_dir = p self.config_file_paths.append(p.location) self._in_init_profile_dir = False
def init_config_files(self): """[optionally] copy default config files into profile dir.""" self.config_file_paths.extend(ENV_CONFIG_DIRS) self.config_file_paths.extend(SYSTEM_CONFIG_DIRS) # copy config files path = Path(self.builtin_profile_dir) if self.copy_config_files: src = self.profile
cfg = self.config_file_name if path and (path / cfg).exists(): self.log.warning( "Staging %r from %s into %r [overwrite=%s]" % (cfg, src, self.profile_dir.location, self.overwrite) ) self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite) else: self.stage_default_config_file() else: # Still stage *bundled* config files, but not generated ones # This is necessary for `ipython profile=sympy` to load the profile # on the first go files = path.glob("*.py") for fullpath in files: cfg = fullpath.name if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False): # file was copied self.log.warning("Staging bundled %s from %s into %r"%( cfg, self.profile, self.profile_dir.location) )
def stage_default_config_file(self): """auto generate default config file, and stage it into the profile.""" s = self.generate_config_file() config_file = Path(self.profile_dir.location) / self.config_file_name if self.overwrite or not config_file.exists(): self.log.warning("Generating default config file: %r", (config_file)) config_file.write_text(s, encoding="utf-8")
@catch_config_error def initialize(self, argv=None): # don't hook up crash handler before parsing command-line self.parse_command_line(argv) self.init_crash_handler() if self.subapp is not None: # stop here if subapp is taking over return # save a copy of CLI config to re-load after config files # so that it has highest priority cl_config = deepcopy(self.config) self.init_profile_dir() self.init_config_files() self.load_config_file() # enforce cl-opts override configfile opts: self.update_config(cl_config)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Async helper function that are invalid syntax on Python 3.5 and below.
This code is best effort, and may have edge cases not behaving as expected. Inparticular it contain a number of heuristics to detect whether code iseffectively async and need to run in an event loop or not.
Some constructs (like top-level `return`, or `yield`) are taken care ofexplicitly to actually raise a SyntaxError and stay as close as possible toPython semantics."""
import astimport asyncioimport inspectfrom functools import wraps
_asyncio_event_loop = None
def get_asyncio_loop(): """asyncio has deprecated get_event_loop
Replicate it here, with our desired semantics:
- always returns a valid, not-closed loop - not thread-local like asyncio's, because we only want one loop for IPython - if called from inside a coroutine (e.g. in ipykernel), return the running loop
.. versionadded:: 8.0 """ try: return asyncio.get_running_loop() except RuntimeError: # not inside a coroutine, # track our own global pass
# not thread-local like asyncio's, # because we only track one event loop to run for IPython itself, # always in the main thread. global _asyncio_event_loop if _asyncio_event_loop is None or _asyncio_event_loop.is_closed(): _asyncio_event_loop = asyncio.new_event_loop() return _asyncio_event_loop
class _AsyncIORunner: def __call__(self, coro): """ Handler for asyncio autoawait """ return get_asyncio_loop().run_until_complete(coro)
def __str__(self): return "asyncio"
_asyncio_runner = _AsyncIORunner()
class _AsyncIOProxy: """Proxy-object for an asyncio
Any coroutine methods will be wrapped in event_loop.run_ """
def __init__(self, obj, event_loop): self._obj = obj self._event_loop = event_loop
def __repr__(self): return f"<_AsyncIOProxy({self._obj!r})>"
def __getattr__(self, key): attr = getattr(self._obj, key) if inspect.iscoroutinefunction(attr): # if it's a coroutine method, # return a threadsafe wrapper onto the _current_ asyncio loop @wraps(attr) def _wrapped(*args, **kwargs): concurrent_future = asyncio.run_coroutine_threadsafe( attr(*args, **kwargs), self._event_loop ) return asyncio.wrap_future(concurrent_future)
return _wrapped else: return attr
def __dir__(self): return dir(self._obj)
def _curio_runner(coroutine): """ handler for curio autoawait """ import curio
return curio.run(coroutine)
def _trio_runner(async_fn): import trio
async def loc(coro): """ We need the dummy no-op async def to protect from trio's internal. See https://github.com/python-trio/trio/issues/89 """ return await coro
return trio.run(loc, async_fn)
def _pseudo_sync_runner(coro): """ A runner that does not really allow async execution, and just advance the coroutine.
See discussion in https://github.com/python-trio/trio/issues/608,
Credit to Nathaniel Smith """ try: coro.send(None) except StopIteration as exc: return exc.value else: # TODO: do not raise but return an execution result with the right info. raise RuntimeError( "{coro_name!r} needs a real async loop".format(coro_name=coro.__name__) )
def _should_be_async(cell: str) -> bool: """Detect if a block of code needs to be wrapped in an `async def`
If the code block has a top-level return statement or is otherwise invalid, `False` will be returned. """ try: code = compile( cell, "<>", "exec", flags=getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0) ) return inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE except (SyntaxError, ValueError, MemoryError): return False12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# encoding: utf-8"""Autocall capabilities for IPython.core.
Authors:
* Brian Granger* Fernando Perez* Thomas Kluyver
Notes-----"""
#-----------------------------------------------------------------------------# Copyright (C) 2008-2011 The IPython Development Team## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Code#-----------------------------------------------------------------------------
class IPyAutocall: """ Instances of this class are always autocalled This happens regardless of 'autocall' variable state. Use this to develop macro-like mechanisms. """ _ip = None rewrite = True def __init__(self, ip=None): self._ip = ip def set_ip(self, ip): """Will be used to set _ip point to current ipython instance b/f call
Override this method if you don't want this to happen.
""" self._ip = ip
class ExitAutocall(IPyAutocall): """An autocallable object which will be added to the user namespace so that exit, exit(), quit or quit() are all valid ways to close the shell.""" rewrite = False def __call__(self): self._ip.ask_exit() class ZMQExitAutocall(ExitAutocall): """Exit IPython. Autocallable, so it needn't be explicitly called. Parameters ---------- keep_kernel : bool If True, leave the kernel alive. Otherwise, tell the kernel to exit too (default). """ def __call__(self, keep_kernel=False): self._ip.keepkernel_on_exit = keep_kernel self._ip.ask_exit()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""A context manager for managing things injected into :mod:`builtins`."""# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.import builtins as builtin_mod
from traitlets.config.configurable import Configurable
from traitlets import Instance
class __BuiltinUndefined: pass
BuiltinUndefined = __BuiltinUndefined()
class __HideBuiltin: pass
HideBuiltin = __HideBuiltin()
class BuiltinTrap(Configurable):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None): super(BuiltinTrap, self).__init__(shell=shell, config=None) self._orig_builtins = {} # We define this to track if a single BuiltinTrap is nested. # Only turn off the trap when the outermost call to __exit__ is made. self._nested_level = 0 self.shell = shell # builtins we always add - if set to HideBuiltin, they will just # be removed instead of being replaced by something else self.auto_builtins = {'exit': HideBuiltin, 'quit': HideBuiltin, 'get_ipython': self.shell.get_ipython, }
def __enter__(self): if self._nested_level == 0: self.activate() self._nested_level += 1 # I return self, so callers can use add_builtin in a with clause. return self
def __exit__(self, type, value, traceback): if self._nested_level == 1: self.deactivate() self._nested_level -= 1 # Returning False will cause exceptions to propagate return False
def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = builtin_mod.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value
def remove_builtin(self, key, orig): """Remove an added builtin and re-set the original.""" if orig is BuiltinUndefined: del builtin_mod.__dict__[key] else: builtin_mod.__dict__[key] = orig
def activate(self): """Store ipython references in the __builtin__ namespace."""
add_builtin = self.add_builtin for name, func in self.auto_builtins.items(): add_builtin(name, func)
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.items(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376"""Pdb debugger class.
This is an extension to PDB which adds a number of new features.Note that there is also the `IPython.terminal.debugger` class which provides UIimprovements.
We also strongly recommend to use this via the `ipdb` package, which providesextra configuration options.
Among other things, this subclass of PDB: - supports many IPython magics like pdef/psource - hide frames in tracebacks based on `__tracebackhide__` - allows to skip frames based on `__debuggerskip__`
Global Configuration--------------------
The IPython debugger will by read the global ``~/.pdbrc`` file.That is to say you can list all commands supported by ipdb in your `~/.pdbrc`configuration file, to globally configure pdb.
Example::
# ~/.pdbrc skip_predicates debuggerskip false skip_hidden false context 25
Features--------
The IPython debugger can hide and skip frames when printing or moving throughthe stack. This can have a performance impact, so can be configures.
The skipping and hiding frames are configurable via the `skip_predicates`command.
By default, frames from readonly files will be hidden, frames containing``__tracebackhide__ = True`` will be hidden.
Frames containing ``__debuggerskip__`` will be stepped over, frames whose parentframes value of ``__debuggerskip__`` is ``True`` will also be skipped.
>>> def helpers_helper(): ... pass ... ... def helper_1(): ... print("don't step in me") ... helpers_helpers() # will be stepped over unless breakpoint set. ... ... ... def helper_2(): ... print("in me neither") ...
One can define a decorator that wraps a function between the two helpers:
>>> def pdb_skipped_decorator(function): ... ... ... def wrapped_fn(*args, **kwargs): ... __debuggerskip__ = True ... helper_1() ... __debuggerskip__ = False ... result = function(*args, **kwargs) ... __debuggerskip__ = True ... helper_2() ... # setting __debuggerskip__ to False again is not necessary ... return result ... ... return wrapped_fn
When decorating a function, ipdb will directly step into ``bar()`` bydefault:
>>> @foo_decorator ... def bar(x, y): ... return x * y
You can toggle the behavior with
ipdb> skip_predicates debuggerskip false
or configure it in your ``.pdbrc``
License-------
Modified from the standard pdb.Pdb class to avoid including readline, so thatthe command line completion of other programs which include this isn'tdamaged.
In the future, this class will be expanded with improvements over the standardpdb.
The original code in this file is mainly lifted out of cmd.py in Python 2.2,with minor changes. Licensing should therefore be under the standard Pythonterms. For details on the PSF (Python Software Foundation) standard license,see:
https://docs.python.org/2/license.html
All the changes since then are under the same license as IPython.
"""
# *****************************************************************************## This file is licensed under the PSF license.## Copyright (C) 2001 Python Software Foundation, www.python.org# Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>### *****************************************************************************
from __future__ import annotations
import inspectimport linecacheimport osimport reimport sysimport warningsfrom contextlib import contextmanagerfrom functools import lru_cache
from IPython import get_ipythonfrom IPython.core.debugger_backport import PdbClosureBackportfrom IPython.utils import PyColorizefrom IPython.utils.PyColorize import TokenStream
from typing import TYPE_CHECKINGfrom types import FrameType
# We have to check this directly from sys.argv, config struct not yet availablefrom pdb import Pdb as _OldPdbfrom pygments.token import Token
if sys.version_info < (3, 13):
class OldPdb(PdbClosureBackport, _OldPdb): pass
else: OldPdb = _OldPdb
if TYPE_CHECKING: # otherwise circular import from IPython.core.interactiveshell import InteractiveShell
# skip module docstests__skip_doctest__ = True
prompt = "ipdb> "
# Allow the set_trace code to operate outside of an ipython instance, even if# it does so with some limitations. The rest of this support is implemented in# the Tracer constructor.
DEBUGGERSKIP = "__debuggerskip__"
# this has been implemented in Pdb in Python 3.13 (https://github.com/python/cpython/pull/106676# on lower python versions, we backported the feature.CHAIN_EXCEPTIONS = sys.version_info < (3, 13)
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. It is still around only because it is still imported by ipdb.", )
RGX_EXTRA_INDENT = re.compile(r"(?<=\n)\s+")
def strip_indentation(multiline_string): return RGX_EXTRA_INDENT.sub("", multiline_string)
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
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.
"""
shell: InteractiveShell _theme_name: str _context: int
_chained_exceptions: tuple[Exception, ...] _chained_exception_index: int
if CHAIN_EXCEPTIONS: MAX_CHAINED_EXCEPTION_DEPTH = 999
default_predicates = { "tbhide": True, "readonly": False, "ipython_internal": True, "debuggerskip": True, }
def __init__( self, completekey=None, stdin=None, stdout=None, context: int | None | str = 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. """ # ipdb issue, see https://github.com/ipython/ipython/issues/14811 if context is None: context = 5 if isinstance(context, str): context = int(context) self.context = context
# `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`. OldPdb.__init__(self, completekey, stdin, stdout, **kwargs) # Python 3.15+ should define this, so no need to initialize # this avoids some getattr(self, 'curframe') if sys.version_info < (3, 15): self.curframe = None
# 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
self.aliases = {}
theme_name = self.shell.colors assert isinstance(theme_name, str) assert theme_name.lower() == theme_name
# Add a python parser so we can syntax highlight source while # debugging. self.parser = PyColorize.Parser(theme_name=theme_name) self.set_theme_name(theme_name)
# 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
if CHAIN_EXCEPTIONS: self._chained_exceptions = tuple() self._chained_exception_index = 0
@property def context(self) -> int: return self._context
@context.setter def context(self, value: int | str) -> None: # ipdb issue see https://github.com/ipython/ipython/issues/14811 if not isinstance(value, int): value = int(value) assert isinstance(value, int) assert value >= 0 self._context = value
def set_theme_name(self, name): assert name.lower() == name assert isinstance(name, str) self._theme_name = name self.parser.theme_name = name
@property def theme(self): return PyColorize.theme_table[self._theme_name]
# def set_colors(self, scheme): """Shorthand access to the color table scheme selector method.""" warnings.warn( "set_colors is deprecated since IPython 9.0, use set_theme_name instead", DeprecationWarning, stacklevel=2, ) assert scheme == scheme.lower() self._theme_name = scheme.lower() self.parser.theme_name = scheme.lower()
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 get_stack(self, *args, **kwargs): stack, pos = super().get_stack(*args, **kwargs) if len(stack) >= 0 and self._is_internal_frame(stack[0][0]): stack.pop(0) pos -= 1 return stack, pos
def _is_internal_frame(self, frame): """Determine if this frame should be skipped as internal""" filename = frame.f_code.co_filename
# Skip bdb.py runcall and internal operations if filename.endswith("bdb.py"): func_name = frame.f_code.co_name # Skip internal bdb operations but allow breakpoint hits if func_name in ("runcall", "run", "runeval"): return True
return False
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
if CHAIN_EXCEPTIONS:
def _get_tb_and_exceptions(self, tb_or_exc): """ Given a tracecack or an exception, return a tuple of chained exceptions and current traceback to inspect. This will deal with selecting the right ``__cause__`` or ``__context__`` as well as handling cycles, and return a flattened list of exceptions we can jump to with do_exceptions. """ _exceptions = [] if isinstance(tb_or_exc, BaseException): traceback, current = tb_or_exc.__traceback__, tb_or_exc
while current is not None: if current in _exceptions: break _exceptions.append(current) if current.__cause__ is not None: current = current.__cause__ elif ( current.__context__ is not None and not current.__suppress_context__ ): current = current.__context__
if len(_exceptions) >= self.MAX_CHAINED_EXCEPTION_DEPTH: self.message( f"More than {self.MAX_CHAINED_EXCEPTION_DEPTH}" " chained exceptions found, not all exceptions" "will be browsable with `exceptions`." ) break else: traceback = tb_or_exc return tuple(reversed(_exceptions)), traceback
@contextmanager def _hold_exceptions(self, exceptions): """ Context manager to ensure proper cleaning of exceptions references When given a chained exception instead of a traceback, pdb may hold references to many objects which may leak memory. We use this context manager to make sure everything is properly cleaned """ try: self._chained_exceptions = exceptions self._chained_exception_index = len(exceptions) - 1 yield finally: # we can't put those in forget as otherwise they would # be cleared on exception change self._chained_exceptions = tuple() self._chained_exception_index = 0
def do_exceptions(self, arg): """exceptions [number] List or change current exception in an exception chain. Without arguments, list all the current exception in the exception chain. Exceptions will be numbered, with the current exception indicated with an arrow. If given an integer as argument, switch to the exception at that index. """ if not self._chained_exceptions: self.message( "Did not find chained exceptions. To move between" " exceptions, pdb/post_mortem must be given an exception" " object rather than a traceback." ) return if not arg: for ix, exc in enumerate(self._chained_exceptions): prompt = ">" if ix == self._chained_exception_index else " " rep = repr(exc) if len(rep) > 80: rep = rep[:77] + "..." indicator = ( " -" if self._chained_exceptions[ix].__traceback__ is None else f"{ix:>3}" ) self.message(f"{prompt} {indicator} {rep}") else: try: number = int(arg) except ValueError: self.error("Argument must be an integer") return if 0 <= number < len(self._chained_exceptions): if self._chained_exceptions[number].__traceback__ is None: self.error( "This exception does not have a traceback, cannot jump to it" ) return
self._chained_exception_index = number self.setup(None, self._chained_exceptions[number].__traceback__) self.print_stack_entry(self.stack[self.curindex]) else: self.error("No exception with that number")
def interaction(self, frame, tb_or_exc): try: if CHAIN_EXCEPTIONS: # this context manager is part of interaction in 3.13 _chained_exceptions, tb = self._get_tb_and_exceptions(tb_or_exc) if isinstance(tb_or_exc, BaseException): assert tb is not None, "main exception must have a traceback" with self._hold_exceptions(_chained_exceptions): OldPdb.interaction(self, frame, tb) else: OldPdb.interaction(self, frame, tb_or_exc)
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_quit(self, arg): return OldPdb.do_quit(self, arg)
do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
def print_stack_trace(self, context: int | None = None): if context is None: context = self.context try: skipped = 0 to_print = "" for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack): if hidden and self.skip_hidden: skipped += 1 continue if skipped: to_print += self.theme.format( [ ( Token.ExcName, f" [... skipping {skipped} hidden frame(s)]", ), (Token, "\n"), ] )
skipped = 0 to_print += self.format_stack_entry(frame_lineno) if skipped: to_print += self.theme.format( [ ( Token.ExcName, f" [... skipping {skipped} hidden frame(s)]", ), (Token, "\n"), ] ) print(to_print, file=self.stdout) except KeyboardInterrupt: pass
def print_stack_entry( self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> " ) -> None: """ Overwrite print_stack_entry from superclass (PDB) """ print(self.format_stack_entry(frame_lineno, ""), file=self.stdout)
frame, lineno = frame_lineno filename = frame.f_code.co_filename self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
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: tuple[FrameType, int], # type: ignore[override] # stubs are wrong lprefix: str = ": ", ) -> str: """ overwrite from super class so must -> str """ 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_tok = []
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_tok.extend([(Token, return_value)])
# s = filename + '(' + `lineno` + ')' filename = self.canonic(frame.f_code.co_filename) link_tok = (Token.FilenameEm, filename)
if frame.f_code.co_name: func = frame.f_code.co_name else: func = "<lambda>"
call_toks = [] if func != "?": if "__args__" in loc_frame: args = reprlib.repr(loc_frame["__args__"]) else: args = "()" call_toks = [(Token.VName, func), (Token.ValEm, 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_tok.append((Token.CurrentFrame, self.theme.make_arrow(2))) else: ret_tok.append((Token, " "))
ret_tok.extend( [ link_tok, (Token, "("), (Token.Lineno, str(lineno)), (Token, ")"), *call_toks, (Token, "\n"), ] )
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
bp, num, colored_line = self.__line_content( filename, start + 1 + i, line, arrow=show_arrow, ) if frame is self.curframe or show_arrow: rlt = [ bp, (Token.LinenoEm, num), (Token, " "), # TODO: investigate Toke.Line here, likely LineEm, # Token is problematic here as line is already colored, a # and this changes the full style of the colored line. # ideally, __line_content returns the token and we modify the style. (Token, colored_line), ] else: rlt = [ bp, (Token.Lineno, num), (Token, " "), # TODO: investigate Toke.Line here, likely Line # Token is problematic here as line is already colored, a # and this changes the full style of the colored line. # ideally, __line_content returns the token and we modify the style. (Token.Line, colored_line), ] ret_tok.extend(rlt)
return self.theme.format(ret_tok)
def __line_content( self, filename: str, lineno: int, line: str, arrow: bool = False ): bp_mark = "" BreakpointToken = Token.Breakpoint
new_line, err = self.parser.format2(line, "str") if not err: assert new_line is not None line = new_line
bp = None if lineno in self.get_file_breaks(filename): bps = self.get_breaks(filename, lineno) bp = bps[-1]
if bp: bp_mark = str(bp.number) BreakpointToken = Token.Breakpoint.Enabled if not bp.enabled: BreakpointToken = Token.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" % (self.theme.make_arrow(pad), str(lineno)) else: num = "%*s" % (numbers_width - len(bp_mark), str(lineno)) bp_str = (BreakpointToken, bp_mark) return (bp_str, num, line)
def print_list_lines(self, filename: str, first: int, last: int) -> None: """The printing (as opposed to the parsing part of a 'list' command.""" toks: TokenStream = [] try: 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
assert self.curframe is not None
if lineno == self.curframe.f_lineno: bp, num, colored_line = self.__line_content( filename, lineno, line, arrow=True ) toks.extend( [ bp, (Token.LinenoEm, num), (Token, " "), # TODO: investigate Token.Line here (Token, colored_line), ] ) else: bp, num, colored_line = self.__line_content( filename, lineno, line, arrow=False ) toks.extend( [ bp, (Token.Lineno, num), (Token, " "), (Token, colored_line), ] )
self.lineno = lineno
print(self.theme.format(toks), 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 and 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 or arg == ".": assert self.curframe is not None first = max(1, self.curframe.f_lineno - 5) else: first = self.lineno + 1 if last is None: last = first + 10 assert self.curframe is not None self.print_list_lines(self.curframe.f_code.co_filename, first, last)
lineno = first filename = self.curframe.f_code.co_filename self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
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(str(err)) return last = lineno + len(lines) assert self.curframe is not None 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) assert self.curframe is not 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""" assert self.curframe is not None 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.""" assert self.curframe is not None 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. """ assert self.curframe is not None 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?.""" assert self.curframe is not None 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??.""" assert self.curframe is not None 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.""" assert self.curframe is not None namespaces = [ ("Locals", self.curframe_locals), ("Globals", self.curframe.f_globals), ] self.shell.find_line_magic("psource")(arg, namespaces=namespaces)
def do_where(self, arg: str): """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(str(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
return self._cachable_skip(frame)
@lru_cache(1024) def _cached_one_parent_frame_debuggerskip(self, frame): """ Cache looking up for DEBUGGERSKIP on parent frame.
This should speedup walking through deep frame when one of the highest one does have a debugger skip.
This is likely to introduce fake positive though. """ while getattr(frame, "f_back", None): frame = frame.f_back if self._get_frame_locals(frame).get(DEBUGGERSKIP): return True return None
@lru_cache(1024) def _cachable_skip(self, frame): # 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. if self._cached_one_parent_frame_debuggerskip(frame): 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: print( self.theme.format( [ ( Token.ExcName, " [... skipped 1 hidden frame(s)]", ), (Token, "\n"), ] ) ) if self.skip and self.is_skipped_module(frame.f_globals.get("__name__", "")): print( self.theme.format( [ ( Token.ExcName, " [... skipped 1 ignored module(s)]", ), (Token, "\n"), ] ) )
return False
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 and ignored modules. """ # modified version of upstream that skips # frames with __tracebackhide__ and ignored modules 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
hidden_skipped = 0 module_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): should_skip_hidden = hidden_frames[i] and self.skip_hidden should_skip_module = self.skip and self.is_skipped_module( self.stack[i][0].f_globals.get("__name__", "") )
if should_skip_hidden or should_skip_module: if should_skip_hidden: hidden_skipped += 1 if should_skip_module: module_skipped += 1 continue counter += 1 if counter >= count: break else: # if no break occurred. self.error( "all frames above skipped (hidden frames and ignored modules). Use `skip_hidden False` for hidden frames or unignore_module for ignored modules." ) return
_newframe = i self._select_frame(_newframe)
total_skipped = hidden_skipped + module_skipped if total_skipped: print( self.theme.format( [ ( Token.ExcName, f" [... skipped {total_skipped} frame(s): {hidden_skipped} hidden frames + {module_skipped} ignored modules]", ), (Token, "\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 and ignored modules. """ 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 hidden_skipped = 0 module_skipped = 0 hidden_frames = self.hidden_frames(self.stack)
for i in range(self.curindex + 1, len(self.stack)): should_skip_hidden = hidden_frames[i] and self.skip_hidden should_skip_module = self.skip and self.is_skipped_module( self.stack[i][0].f_globals.get("__name__", "") )
if should_skip_hidden or should_skip_module: if should_skip_hidden: hidden_skipped += 1 if should_skip_module: module_skipped += 1 continue counter += 1 if counter >= count: break else: self.error( "all frames below skipped (hidden frames and ignored modules). Use `skip_hidden False` for hidden frames or unignore_module for ignored modules." ) return
total_skipped = hidden_skipped + module_skipped if total_skipped: print( self.theme.format( [ ( Token.ExcName, f" [... skipped {total_skipped} frame(s): {hidden_skipped} hidden frames + {module_skipped} ignored modules]", ), (Token, "\n"), ] ) ) _newframe = i
self._select_frame(_newframe)
do_d = do_down do_u = do_up
def _show_ignored_modules(self): """Display currently ignored modules.""" if self.skip: print(f"Currently ignored modules: {sorted(self.skip)}") else: print("No modules are currently ignored.")
def do_ignore_module(self, arg): """ignore_module <module_name>
Add a module to the list of modules to skip when navigating frames. When a module is ignored, the debugger will automatically skip over frames from that module.
Supports wildcard patterns using fnmatch syntax:
Usage: ignore_module threading # Skip threading module frames ignore_module asyncio.\\* # Skip all asyncio submodules ignore_module \\*.tests # Skip all test modules ignore_module # List currently ignored modules """
if self.skip is None: self.skip = set()
module_name = arg.strip()
if not module_name: self._show_ignored_modules() return
self.skip.add(module_name)
def do_unignore_module(self, arg): """unignore_module <module_name>
Remove a module from the list of modules to skip when navigating frames. This will allow the debugger to step into frames from the specified module.
Usage: unignore_module threading # Stop ignoring threading module frames unignore_module asyncio.\\* # Remove asyncio.* pattern unignore_module # List currently ignored modules """
if self.skip is None: self.skip = set()
module_name = arg.strip()
if not module_name: self._show_ignored_modules() return
try: self.skip.remove(module_name) except KeyError: print(f"Module {module_name} is not currently ignored") self._show_ignored_modules()
def do_context(self, context: str): """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( f"The 'context' command requires a positive integer argument (current value {self.context})." )
class InterruptiblePdb(Pdb): """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
def cmdloop(self, intro=None): """Wrap cmdloop() such that KeyboardInterrupt stops the debugger.""" try: return OldPdb.cmdloop(self, intro=intro) except KeyboardInterrupt: self.stop_here = lambda frame: False # type: ignore[method-assign] self.do_quit("") sys.settrace(None) self.quitting = False raise
def _cmdloop(self): while True: try: # keyboard interrupts allow for an easy way to cancel # the current command, so allow them during interactive input self.allow_kbdint = True self.cmdloop() self.allow_kbdint = False break except KeyboardInterrupt: self.message("--KeyboardInterrupt--") raise
def set_trace(frame=None, header=None): """ Start debugging from `frame`.
If frame is not specified, debugging starts from caller's frame. """ pdb = Pdb() if header is not None: pdb.message(header) pdb.set_trace(frame or sys._getframe().f_back)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""The code in this module is a backport of cPython changes in Pdbthat were introduced in Python 3.13 by gh-83151: Make closure work on pdbhttps://github.com/python/cpython/pull/111094.This file should be removed once IPython drops supports for Python 3.12.
The only changes are:- reformatting by darker (black) formatter- addition of type-ignore comments to satisfy mypy
Copyright (c) 2001 Python Software Foundation; All Rights Reserved
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation("PSF"), and the Individual or Organization ("Licensee") accessing andotherwise using this software ("Python") in source or binary form andits associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF herebygrants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,analyze, test, perform and/or display publicly, prepare derivative works,distribute, and otherwise use Python alone or in any derivative version,provided, however, that PSF's License Agreement and PSF's notice of copyright,i.e., "Copyright (c) 2001 Python Software Foundation; All Rights Reserved"are retained in Python alone or in any derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based onor incorporates Python or any part thereof, and wants to makethe derivative work available to others as provided herein, thenLicensee hereby agrees to include in any such work a brief summary ofthe changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS ORIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO ANDDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESSFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOTINFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHONFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS ASA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a materialbreach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create anyrelationship of agency, partnership, or joint venture between PSF andLicensee. This License Agreement does not grant permission to use PSFtrademarks or trade name in a trademark sense to endorse or promoteproducts or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licenseeagrees to be bound by the terms and conditions of this LicenseAgreement."""
import sysimport typesimport codeopimport textwrapfrom types import CodeType
class PdbClosureBackport: def _exec_in_closure(self, source, globals, locals): # type: ignore[no-untyped-def] """Run source code in closure so code object created within source can find variables in locals correctly returns True if the source is executed, False otherwise """
# Determine if the source should be executed in closure. Only when the # source compiled to multiple code objects, we should use this feature. # Otherwise, we can just raise an exception and normal exec will be used.
code = compile(source, "<string>", "exec") if not any(isinstance(const, CodeType) for const in code.co_consts): return False
# locals could be a proxy which does not support pop # copy it first to avoid modifying the original locals locals_copy = dict(locals)
locals_copy["__pdb_eval__"] = {"result": None, "write_back": {}}
# If the source is an expression, we need to print its value try: compile(source, "<string>", "eval") except SyntaxError: pass else: source = "__pdb_eval__['result'] = " + source
# Add write-back to update the locals source = ( "try:\n" + textwrap.indent(source, " ") + "\n" + "finally:\n" + " __pdb_eval__['write_back'] = locals()" )
# Build a closure source code with freevars from locals like: # def __pdb_outer(): # var = None # def __pdb_scope(): # This is the code object we want to execute # nonlocal var # <source> # return __pdb_scope.__code__ source_with_closure = ( "def __pdb_outer():\n" + "\n".join(f" {var} = None" for var in locals_copy) + "\n" + " def __pdb_scope():\n" + "\n".join(f" nonlocal {var}" for var in locals_copy) + "\n" + textwrap.indent(source, " ") + "\n" + " return __pdb_scope.__code__" )
# Get the code object of __pdb_scope() # The exec fills locals_copy with the __pdb_outer() function and we can call # that to get the code object of __pdb_scope() ns = {} try: exec(source_with_closure, {}, ns) except Exception: return False code = ns["__pdb_outer"]()
cells = tuple(types.CellType(locals_copy.get(var)) for var in code.co_freevars)
try: exec(code, globals, locals_copy, closure=cells) except Exception: return False
# get the data we need from the statement pdb_eval = locals_copy["__pdb_eval__"]
# __pdb_eval__ should not be updated back to locals pdb_eval["write_back"].pop("__pdb_eval__")
# Write all local variables back to locals locals.update(pdb_eval["write_back"]) eval_result = pdb_eval["result"] if eval_result is not None: print(repr(eval_result))
return True
def default(self, line): # type: ignore[no-untyped-def] if line[:1] == "!": line = line[1:].strip() locals = self.curframe_locals globals = self.curframe.f_globals try: buffer = line if ( code := codeop.compile_command(line + "\n", "<stdin>", "single") ) is None: # Multi-line mode with self._disable_command_completion(): buffer = line continue_prompt = "... " while ( code := codeop.compile_command(buffer, "<stdin>", "single") ) is None: if self.use_rawinput: try: line = input(continue_prompt) except (EOFError, KeyboardInterrupt): self.lastcmd = "" print("\n") return else: self.stdout.write(continue_prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): self.lastcmd = "" self.stdout.write("\n") self.stdout.flush() return else: line = line.rstrip("\r\n") buffer += "\n" + line save_stdout = sys.stdout save_stdin = sys.stdin save_displayhook = sys.displayhook try: sys.stdin = self.stdin sys.stdout = self.stdout sys.displayhook = self.displayhook if not self._exec_in_closure(buffer, globals, locals): exec(code, globals, locals) finally: sys.stdout = save_stdout sys.stdin = save_stdin sys.displayhook = save_displayhook except: self._error_exc()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266"""Top-level display functions for displaying object in different formats."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
from binascii import b2a_base64, hexlifyimport htmlimport jsonimport mimetypesimport osimport structimport warningsfrom copy import deepcopyfrom os.path import splitextfrom pathlib import Path, PurePath
from typing import Optional
from IPython.testing.skipdoctest import skip_doctestfrom . import display_functions
__all__ = [ "display_pretty", "display_html", "display_markdown", "display_svg", "display_png", "display_jpeg", "display_webp", "display_latex", "display_json", "display_javascript", "display_pdf", "DisplayObject", "TextDisplayObject", "Pretty", "HTML", "Markdown", "Math", "Latex", "SVG", "ProgressBar", "JSON", "GeoJSON", "Javascript", "Image", "Video",]
#-----------------------------------------------------------------------------# utility functions#-----------------------------------------------------------------------------
def _safe_exists(path): """Check path, but don't let exceptions raise""" try: return os.path.exists(path) except Exception: return False
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])
#-----------------------------------------------------------------------------# Main functions#-----------------------------------------------------------------------------
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)
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)
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)
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)
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)
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)
def display_webp(*objs, **kwargs): """Display the WEBP representation of an object.
Parameters ---------- *objs : object The Python objects to display, or if raw=True raw JPEG data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [default: False] metadata : dict (optional) Metadata to be associated with the specific mimetype output. """ _display_mimetype("image/webp", objs, **kwargs)
def display_latex(*objs, **kwargs): """Display the LaTeX representation of an object.
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)
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)
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)
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)
#-----------------------------------------------------------------------------# Smart classes#-----------------------------------------------------------------------------
class DisplayObject: """An object that wraps data to be displayed."""
_read_flags = 'r' _show_mem_addr = False metadata = None
def __init__(self, data=None, url=None, filename=None, metadata=None): """Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for 'image/png' data. If the data is a URL, the data will first be downloaded and then displayed.
Parameters ---------- data : unicode, str or bytes The raw data or a URL or file to load the data from url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. metadata : dict Dict of metadata associated to be the object when displayed """ if isinstance(data, (Path, PurePath)): data = str(data)
if data is not None and isinstance(data, str): if data.startswith('http') and url is None: url = data filename = None data = None elif _safe_exists(data) and filename is None: url = None filename = data data = None
self.url = url self.filename = filename # because of @data.setter methods in # subclasses ensure url and filename are set # before assigning to self.data self.data = data
if metadata is not None: self.metadata = metadata elif self.metadata is None: self.metadata = {}
self.reload() self._check_data()
def __repr__(self): if not self._show_mem_addr: cls = self.__class__ r = "<%s.%s object>" % (cls.__module__, cls.__name__) else: r = super(DisplayObject, self).__repr__() return r
def _check_data(self): """Override in subclasses if there's something to check.""" pass
def _data_and_metadata(self): """shortcut for returning metadata with shape information, if defined""" if self.metadata: return self.data, deepcopy(self.metadata) else: return self.data
def reload(self): """Reload the raw data from file or URL.""" if self.filename is not None: encoding = None if "b" in self._read_flags else "utf-8" with open(self.filename, self._read_flags, encoding=encoding) as f: self.data = f.read() elif self.url is not None: # Deferred import from urllib.request import urlopen response = urlopen(self.url) data = response.read() # extract encoding from header, if there is one: encoding = None if 'content-type' in response.headers: for sub in response.headers['content-type'].split(';'): sub = sub.strip() if sub.startswith('charset'): encoding = sub.split('=')[-1].strip() break if 'content-encoding' in response.headers: # TODO: do deflate? if 'gzip' in response.headers['content-encoding']: import gzip from io import BytesIO
# assume utf-8 if encoding is not specified with gzip.open( BytesIO(data), "rt", encoding=encoding or "utf-8" ) as fp: encoding = None data = fp.read()
# decode data, if an encoding was specified # We only touch self.data once since # subclasses such as SVG have @data.setter methods # that transform self.data into ... well svg. if encoding: self.data = data.decode(encoding, 'replace') else: self.data = data
class TextDisplayObject(DisplayObject): """Create a text display object given raw data.
Parameters ---------- data : str or unicode The raw data or a URL or file to load the data from. url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. metadata : dict Dict of metadata associated to be the object when displayed """ def _check_data(self): if self.data is not None and not isinstance(self.data, str): raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
class Pretty(TextDisplayObject):
def _repr_pretty_(self, pp, cycle): return pp.text(self.data)
class HTML(TextDisplayObject):
def __init__(self, data=None, url=None, filename=None, metadata=None): def warn(): if not data: return False
# # Avoid calling lower() on the entire data, because it could be a # long string and we're only interested in its beginning and end. # prefix = data[:10].lower() suffix = data[-10:].lower() return prefix.startswith("<iframe ") and suffix.endswith("</iframe>")
if warn(): warnings.warn("Consider using IPython.display.IFrame instead") super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata)
def _repr_html_(self): return self._data_and_metadata()
def __html__(self): """ This method exists to inform other HTML-using modules (e.g. Markupsafe, htmltag, etc) that this object is HTML and does not need things like special characters (<>&) escaped. """ return self._repr_html_()
class Markdown(TextDisplayObject):
def _repr_markdown_(self): return self._data_and_metadata()
class Math(TextDisplayObject):
def _repr_latex_(self): s = r"$\displaystyle %s$" % self.data.strip('$') if self.metadata: return s, deepcopy(self.metadata) else: return s
class Latex(TextDisplayObject):
def _repr_latex_(self): return self._data_and_metadata()
class SVG(DisplayObject): """Embed an SVG into the display.
Note if you just want to view a svg image via a URL use `:class:Image` with a url=URL keyword argument. """
_read_flags = 'rb' # wrap data in a property, which extracts the <svg> tag, discarding # document headers _data: Optional[str] = None
@property def data(self): return self._data
@data.setter def data(self, svg): if svg is None: self._data = None return # parse into dom object from xml.dom import minidom x = minidom.parseString(svg) # get svg tag (should be 1) found_svg = x.getElementsByTagName('svg') if found_svg: svg = found_svg[0].toxml() else: # fallback on the input, trust the user # but this is probably an error. pass if isinstance(svg, bytes): self._data = svg.decode(errors="replace") else: self._data = svg
def _repr_svg_(self): return self._data_and_metadata()
class ProgressBar(DisplayObject): """Progressbar supports displaying a progressbar like element """ def __init__(self, total): """Creates a new progressbar
Parameters ---------- total : int maximum size of the progressbar """ self.total = total self._progress = 0 self.html_width = '60ex' self.text_width = 60 self._display_id = hexlify(os.urandom(8)).decode('ascii')
def __repr__(self): fraction = self.progress / self.total filled = '=' * int(fraction * self.text_width) rest = ' ' * (self.text_width - len(filled)) return '[{}{}] {}/{}'.format( filled, rest, self.progress, self.total, )
def _repr_html_(self): return "<progress style='width:{}' max='{}' value='{}'></progress>".format( self.html_width, self.total, self.progress)
def display(self): display_functions.display(self, display_id=self._display_id)
def update(self): display_functions.display(self, display_id=self._display_id, update=True)
@property def progress(self): return self._progress
@progress.setter def progress(self, value): self._progress = value self.update()
def __iter__(self): self.display() self._progress = -1 # First iteration is 0 return self
def __next__(self): """Returns current value and increments display by one.""" self.progress += 1 if self.progress < self.total: return self.progress else: raise StopIteration()
class JSON(DisplayObject): """JSON expects a JSON-able dict or list
not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict or list containers. """ # wrap data in a property, which warns about passing already-serialized JSON _data = None def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs): """Create a JSON display object given raw data.
Parameters ---------- data : dict or list JSON data to display. Not an already-serialized JSON string. Scalar types (None, number, string) are not allowed, only dict or list containers. url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. expanded : boolean Metadata to control whether a JSON display component is expanded. metadata : dict Specify extra metadata to attach to the json display object. root : str The name of the root element of the JSON tree """ self.metadata = { 'expanded': expanded, 'root': root, } if metadata: self.metadata.update(metadata) if kwargs: self.metadata.update(kwargs) super(JSON, self).__init__(data=data, url=url, filename=filename)
def _check_data(self): if self.data is not None and not isinstance(self.data, (dict, list)): raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
@property def data(self): return self._data
@data.setter def data(self, data): if isinstance(data, (Path, PurePath)): data = str(data)
if isinstance(data, str): if self.filename is None and self.url is None: warnings.warn("JSON expects JSONable dict or list, not JSON strings") data = json.loads(data) self._data = data
def _data_and_metadata(self): return self.data, self.metadata
def _repr_json_(self): return self._data_and_metadata()
_css_t = """var link = document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = "%s"; document.head.appendChild(link);"""
_lib_t1 = """new Promise(function(resolve, reject) { var script = document.createElement("script"); script.onload = resolve; script.onerror = reject; script.src = "%s"; document.head.appendChild(script);}).then(() => {"""
_lib_t2 = """});"""
class GeoJSON(JSON): """GeoJSON expects JSON-able dict
not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict containers. """
def __init__(self, *args, **kwargs): """Create a GeoJSON display object given raw data.
Parameters ---------- data : dict or list VegaLite data. Not an already-serialized JSON string. Scalar types (None, number, string) are not allowed, only dict or list containers. url_template : string Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template layer_options : dict Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. metadata : dict Specify extra metadata to attach to the json display object.
Examples -------- The following will display an interactive map of Mars with a point of interest on frontend that do support GeoJSON display.
>>> from IPython.display import GeoJSON
>>> GeoJSON(data={ ... "type": "Feature", ... "geometry": { ... "type": "Point", ... "coordinates": [-81.327, 296.038] ... } ... }, ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", ... layer_options={ ... "basemap_id": "celestia_mars-shaded-16k_global", ... "attribution" : "Celestia/praesepe", ... "minZoom" : 0, ... "maxZoom" : 18, ... }) <IPython.core.display.GeoJSON object>
In the terminal IPython, you will only see the text representation of the GeoJSON object.
"""
super(GeoJSON, self).__init__(*args, **kwargs)
def _ipython_display_(self): bundle = { 'application/geo+json': self.data, 'text/plain': '<IPython.display.GeoJSON object>' } metadata = { 'application/geo+json': self.metadata } display_functions.display(bundle, metadata=metadata, raw=True)
class Javascript(TextDisplayObject):
def __init__(self, data=None, url=None, filename=None, lib=None, css=None): """Create a Javascript display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. If the data is a URL, the data will first be downloaded and then displayed.
In the Notebook, the containing element will be available as `element`, and jQuery will be available. Content appended to `element` will be visible in the output area.
Parameters ---------- data : unicode, str or bytes The Javascript source code or a URL to download it from. url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. lib : list or str A sequence of Javascript library URLs to load asynchronously before running the source code. The full URLs of the libraries should be given. A single Javascript library URL can also be given as a string. css : list or str A sequence of css files to load before running the source code. The full URLs of the css files should be given. A single css URL can also be given as a string. """ if isinstance(lib, str): lib = [lib] elif lib is None: lib = [] if isinstance(css, str): css = [css] elif css is None: css = [] if not isinstance(lib, (list,tuple)): raise TypeError('expected sequence, got: %r' % lib) if not isinstance(css, (list,tuple)): raise TypeError('expected sequence, got: %r' % css) self.lib = lib self.css = css super(Javascript, self).__init__(data=data, url=url, filename=filename)
def _repr_javascript_(self): r = '' for c in self.css: r += _css_t % c for l in self.lib: r += _lib_t1 % l r += self.data r += _lib_t2*len(self.lib) return r
# constants for identifying png/jpeg/gif/webp data_PNG = b"\x89PNG\r\n\x1a\n"_JPEG = b"\xff\xd8"_GIF1 = b"GIF87a"_GIF2 = b"GIF89a"_WEBP = b"WEBP"
def _pngxy(data): """read the (width, height) from a PNG header""" ihdr = data.index(b'IHDR') # next 8 bytes are width/height return struct.unpack('>ii', data[ihdr+4:ihdr+12])
def _jpegxy(data): """read the (width, height) from a JPEG header""" # adapted from http://www.64lines.com/jpeg-width-height
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
def _gifxy(data): """read the (width, height) from a GIF header""" return struct.unpack('<HH', data[6:10])
def _webpxy(data): """read the (width, height) from a WEBP header""" if data[12:16] == b"VP8 ": width, height = struct.unpack("<HH", data[24:30]) width = width & 0x3FFF height = height & 0x3FFF return (width, height) elif data[12:16] == b"VP8L": size_info = struct.unpack("<I", data[21:25])[0] width = 1 + ((size_info & 0x3F) << 8) | (size_info >> 24) height = 1 + ( (((size_info >> 8) & 0xF) << 10) | (((size_info >> 14) & 0x3FC) << 2) | ((size_info >> 22) & 0x3) ) return (width, height) else: raise ValueError("Not a valid WEBP header")
class Image(DisplayObject):
_read_flags = "rb" _FMT_JPEG = "jpeg" _FMT_PNG = "png" _FMT_GIF = "gif" _FMT_WEBP = "webp" _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF, _FMT_WEBP] _MIMETYPES = { _FMT_PNG: "image/png", _FMT_JPEG: "image/jpeg", _FMT_GIF: "image/gif", _FMT_WEBP: "image/webp", }
def __init__( self, data=None, url=None, filename=None, format=None, embed=None, width=None, height=None, retina=False, unconfined=False, metadata=None, alt=None, ): """Create a PNG/JPEG/GIF/WEBP image object given raw data.
When this object is returned by an input cell or passed to the display function, it will result in the image being displayed in the frontend.
Parameters ---------- data : unicode, str or bytes The raw image data or a URL or filename to load the data from. This always results in embedded image data.
url : unicode A URL to download the data from. If you specify `url=`, the image data will not be embedded unless you also specify `embed=True`.
filename : unicode Path to a local file to load the data from. Images from a file are always embedded.
format : unicode The format of the image data (png/jpeg/jpg/gif/webp). If a filename or URL is given for format will be inferred from the filename extension.
embed : bool Should the image data be embedded using a data URI (True) or be loaded using an <img> tag. Set this to True if you want the image to be viewable later with no internet connection in the notebook.
Default is `True`, unless the keyword argument `url` is set, then default value is `False`.
Note that QtConsole is not able to display images if `embed` is set to `False`
width : int Width in pixels to which to constrain the image in html
height : int Height in pixels to which to constrain the image in html
retina : bool Automatically set the width and height to half of the measured width and height. This only works for embedded images because it reads the width/height from image data. For non-embedded images, you can just set the desired display width and height directly.
unconfined : bool Set unconfined=True to disable max-width confinement of the image.
metadata : dict Specify extra metadata to attach to the image.
alt : unicode Alternative text for the image, for use by screen readers.
Examples -------- embedded image data, works in qtconsole and notebook when passed positionally, the first arg can be any of raw image data, a URL, or a filename from which to load image data. The result is always embedding image data for inline images.
>>> Image('https://www.google.fr/images/srpr/logo3w.png') # doctest: +SKIP <IPython.core.display.Image object>
>>> Image('/path/to/image.jpg') <IPython.core.display.Image object>
>>> Image(b'RAW_PNG_DATA...') <IPython.core.display.Image object>
Specifying Image(url=...) does not embed the image data, it only generates ``<img>`` tag with a link to the source. This will not work in the qtconsole or offline.
>>> Image(url='https://www.google.fr/images/srpr/logo3w.png') <IPython.core.display.Image object>
""" if isinstance(data, (Path, PurePath)): data = str(data)
if filename is not None: ext = self._find_ext(filename) elif url is not None: ext = self._find_ext(url) elif data is None: raise ValueError("No image data found. Expecting filename, url, or data.") elif isinstance(data, str) and ( data.startswith('http') or _safe_exists(data) ): ext = self._find_ext(data) else: ext = None
if format is None: if ext is not None: if ext == u'jpg' or ext == u'jpeg': format = self._FMT_JPEG elif ext == u'png': format = self._FMT_PNG elif ext == u'gif': format = self._FMT_GIF elif ext == "webp": format = self._FMT_WEBP else: format = ext.lower() elif isinstance(data, bytes): # infer image type from image data header, # only if format has not been specified. if data[:2] == _JPEG: format = self._FMT_JPEG elif data[:8] == _PNG: format = self._FMT_PNG elif data[8:12] == _WEBP: format = self._FMT_WEBP elif data[:6] == _GIF1 or data[:6] == _GIF2: format = self._FMT_GIF
# failed to detect format, default png if format is None: format = self._FMT_PNG
if format.lower() == 'jpg': # jpg->jpeg format = self._FMT_JPEG
self.format = format.lower() self.embed = embed if embed is not None else (url is None)
if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: raise ValueError("Cannot embed the '%s' image format" % (self.format)) if self.embed: self._mimetype = self._MIMETYPES.get(self.format)
self.width = width self.height = height self.retina = retina self.unconfined = unconfined self.alt = alt super(Image, self).__init__(data=data, url=url, filename=filename, metadata=metadata)
if self.width is None and self.metadata.get('width', {}): self.width = metadata['width']
if self.height is None and self.metadata.get('height', {}): self.height = metadata['height']
if self.alt is None and self.metadata.get("alt", {}): self.alt = metadata["alt"]
if retina: self._retina_shape()
def _retina_shape(self): """load pixel-doubled width and height from image data""" if not self.embed: return if self.format == self._FMT_PNG: w, h = _pngxy(self.data) elif self.format == self._FMT_JPEG: w, h = _jpegxy(self.data) elif self.format == self._FMT_GIF: w, h = _gifxy(self.data) else: # retina only supports png return self.width = w // 2 self.height = h // 2
def reload(self): """Reload the raw data from file or URL.""" if self.embed: super(Image,self).reload() if self.retina: self._retina_shape()
def _repr_html_(self): if not self.embed: width = height = klass = alt = "" if self.width: width = ' width="%d"' % self.width if self.height: height = ' height="%d"' % self.height if self.unconfined: klass = ' class="unconfined"' if self.alt: alt = ' alt="%s"' % html.escape(self.alt) return '<img src="{url}"{width}{height}{klass}{alt}/>'.format( url=self.url, width=width, height=height, klass=klass, alt=alt, )
def _repr_mimebundle_(self, include=None, exclude=None): """Return the image as a mimebundle
Any new mimetype support should be implemented here. """ if self.embed: mimetype = self._mimetype data, metadata = self._data_and_metadata(always_both=True) if metadata: metadata = {mimetype: metadata} return {mimetype: data}, metadata else: return {'text/html': self._repr_html_()}
def _data_and_metadata(self, always_both=False): """shortcut for returning metadata with shape information, if defined""" try: b64_data = b2a_base64(self.data, newline=False).decode("ascii") except TypeError as e: raise FileNotFoundError( "No such file or directory: '%s'" % (self.data)) from e md = {} if self.metadata: md.update(self.metadata) if self.width: md['width'] = self.width if self.height: md['height'] = self.height if self.unconfined: md['unconfined'] = self.unconfined if self.alt: md["alt"] = self.alt if md or always_both: return b64_data, md else: return b64_data
def _repr_png_(self): if self.embed and self.format == self._FMT_PNG: return self._data_and_metadata()
def _repr_jpeg_(self): if self.embed and self.format == self._FMT_JPEG: return self._data_and_metadata()
def _find_ext(self, s): base, ext = splitext(s)
if not ext: return base
# `splitext` includes leading period, so we skip it return ext[1:].lower()
class Video(DisplayObject):
def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None, width=None, height=None, html_attributes="controls"): """Create a video object given raw data or an URL.
When this object is returned by an input cell or passed to the display function, it will result in the video being displayed in the frontend.
Parameters ---------- data : unicode, str or bytes The raw video data or a URL or filename to load the data from. Raw data will require passing ``embed=True``.
url : unicode A URL for the video. If you specify ``url=``, the image data will not be embedded.
filename : unicode Path to a local file containing the video. Will be interpreted as a local URL unless ``embed=True``.
embed : bool Should the video be embedded using a data URI (True) or be loaded using a <video> tag (False).
Since videos are large, embedding them should be avoided, if possible. You must confirm embedding as your intention by passing ``embed=True``.
Local files can be displayed with URLs without embedding the content, via::
Video('./video.mp4')
mimetype : unicode Specify the mimetype for embedded videos. Default will be guessed from file extension, if available.
width : int Width in pixels to which to constrain the video in HTML. If not supplied, defaults to the width of the video.
height : int Height in pixels to which to constrain the video in html. If not supplied, defaults to the height of the video.
html_attributes : str Attributes for the HTML ``<video>`` block. Default: ``"controls"`` to get video controls. Other examples: ``"controls muted"`` for muted video with controls, ``"loop autoplay"`` for looping autoplaying video without controls.
Examples -------- ::
Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') Video('path/to/video.mp4') Video('path/to/video.mp4', embed=True) Video('path/to/video.mp4', embed=True, html_attributes="controls muted autoplay") Video(b'raw-videodata', embed=True) """ if isinstance(data, (Path, PurePath)): data = str(data)
if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): url = data data = None elif data is not None and os.path.exists(data): filename = data data = None
if data and not embed: msg = ''.join([ "To embed videos, you must pass embed=True ", "(this may make your notebook files huge)\n", "Consider passing Video(url='...')", ]) raise ValueError(msg)
self.mimetype = mimetype self.embed = embed self.width = width self.height = height self.html_attributes = html_attributes super(Video, self).__init__(data=data, url=url, filename=filename)
def _repr_html_(self): width = height = '' if self.width: width = ' width="%d"' % self.width if self.height: height = ' height="%d"' % self.height
# External URLs and potentially local files are not embedded into the # notebook output. if not self.embed: url = self.url if self.url is not None else self.filename output = """<video src="{0}" {1} {2} {3}> Your browser does not support the <code>video</code> element. </video>""".format(url, self.html_attributes, width, height) return output
# Embedded videos are base64-encoded. mimetype = self.mimetype if self.filename is not None: if not mimetype: mimetype, _ = mimetypes.guess_type(self.filename)
with open(self.filename, 'rb') as f: video = f.read() else: video = self.data if isinstance(video, str): # unicode input is already b64-encoded b64_video = video else: b64_video = b2a_base64(video, newline=False).decode("ascii").rstrip()
output = """<video {0} {1} {2}> <source src="data:{3};base64,{4}" type="{3}"> Your browser does not support the video tag. </video>""".format(self.html_attributes, width, height, mimetype, b64_video) return output
def reload(self): # TODO pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371"""Top-level display functions for displaying object in different formats."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
from binascii import b2a_heximport osimport sysimport warnings
__all__ = ['display', 'clear_output', 'publish_display_data', 'update_display', 'DisplayHandle']
#-----------------------------------------------------------------------------# utility functions#-----------------------------------------------------------------------------
def _merge(d1, d2): """Like update, but merges sub-dicts instead of clobbering at the top level.
Updates d1 in-place """
if not isinstance(d2, dict) or not isinstance(d1, dict): return d2 for key, value in d2.items(): d1[key] = _merge(d1.get(key), value) return d1
#-----------------------------------------------------------------------------# Main functions#-----------------------------------------------------------------------------
# use * to indicate transient is keyword-onlydef publish_display_data(data, metadata=None, *, transient=None, **kwargs): """Publish data and metadata to all frontends.
See the ``display_data`` message in the messaging documentation for more details about this message type.
Keys of data and metadata can be any mime-type.
Parameters ---------- data : dict A dictionary having keys that are valid MIME types (like 'text/plain' or 'image/svg+xml') and values that are the data for that MIME type. The data itself must be a JSON'able data structure. Minimally all data should have the 'text/plain' data, which can be displayed by all frontends. If more than the plain text is given, it is up to the frontend to decide which representation to use. metadata : dict A dictionary for metadata related to the data. This can contain arbitrary key, value pairs that frontends can use to interpret the data. mime-type keys matching those in data can be used to specify metadata about particular representations. transient : dict, keyword-only A dictionary of transient data, such as display_id. """ from IPython.core.interactiveshell import InteractiveShell
display_pub = InteractiveShell.instance().display_pub
# only pass transient if supplied, # to avoid errors with older ipykernel. # TODO: We could check for ipykernel version and provide a detailed upgrade message. if transient: kwargs['transient'] = transient
display_pub.publish( data=data, metadata=metadata, **kwargs )
def _new_id(): """Generate a new random text id with urandom""" return b2a_hex(os.urandom(16)).decode('ascii')
def display( *objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, raw=False, clear=False, **kwargs,): """Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how.
In terminal IPython this will be similar to using :func:`print`, for use in richer frontends see Jupyter notebook examples with rich display logic.
Parameters ---------- *objs : object The Python objects to display. raw : bool, optional Are the objects to be displayed already mimetype-keyed dicts of raw display data, or Python objects that need to be formatted before display? [default: False] include : list, tuple or set, optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list, tuple or set, optional A list of format type strings (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument. metadata : dict, optional A dictionary of metadata to associate with the output. mime-type keys in this dictionary will be associated with the individual representation formats, if they exist. transient : dict, optional A dictionary of transient data to associate with the output. Data in this dict should not be persisted to files (e.g. notebooks). display_id : str, bool optional Set an id for the display. This id can be used for updating this display area later via update_display. If given as `True`, generate a new `display_id` clear : bool, optional Should the output area be cleared before displaying anything? If True, this will wait for additional output before clearing. [default: False] **kwargs : additional keyword-args, optional Additional keyword-arguments are passed through to the display publisher.
Returns ------- handle: DisplayHandle Returns a handle on updatable displays for use with :func:`update_display`, if `display_id` is given. Returns :py:data:`None` if no `display_id` is given (default).
Examples -------- >>> class Json(object): ... def __init__(self, json): ... self.json = json ... def _repr_pretty_(self, pp, cycle): ... import json ... pp.text(json.dumps(self.json, indent=2)) ... def __repr__(self): ... return str(self.json) ...
>>> d = Json({1:2, 3: {4:5}})
>>> print(d) {1: 2, 3: {4: 5}}
>>> display(d) { "1": 2, "3": { "4": 5 } }
>>> def int_formatter(integer, pp, cycle): ... pp.text('I'*integer)
>>> plain = get_ipython().display_formatter.formatters['text/plain'] >>> plain.for_type(int, int_formatter) <function _repr_pprint at 0x...> >>> display(7-5) II
>>> del plain.type_printers[int] >>> display(7-5) 2
See Also -------- :func:`update_display`
Notes ----- In Python, objects can declare their textual representation using the `__repr__` method. IPython expands on this idea and allows objects to declare other, rich representations including:
- HTML - JSON - PNG - JPEG - SVG - LaTeX
A single object can declare some or all of these representations; all are handled by IPython's display system.
The main idea of the first approach is that you have to implement special display methods when you define your class, one for each representation you want to use. Here is a list of the names of the special methods and the values they must return:
- `_repr_html_`: return raw HTML as a string, or a tuple (see below). - `_repr_json_`: return a JSONable dict, or a tuple (see below). - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). - `_repr_png_`: return raw PNG data, or a tuple (see below). - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). - `_repr_latex_`: return LaTeX commands in a string surrounded by "$", or a tuple (see below). - `_repr_mimebundle_`: return a full mimebundle containing the mapping from all mimetypes to data. Use this for any mime-type not listed above.
The above functions may also return the object's metadata alonside the data. If the metadata is available, the functions will return a tuple containing the data and metadata, in that order. If there is no metadata available, then the functions will return the data only.
When you are directly writing your own classes, you can adapt them for display in IPython by following the above approach. But in practice, you often need to work with existing classes that you can't easily modify.
You can refer to the documentation on integrating with the display system in order to register custom formatters for already existing types (:ref:`integrating_rich_display`).
.. versionadded:: 5.4 display available without import .. versionadded:: 6.1 display available without import
Since IPython 5.4 and 6.1 :func:`display` is automatically made available to the user without import. If you are using display in a document that might be used in a pure python context or with older version of IPython, use the following import at the top of your file::
from IPython.display import display
""" from IPython.core.interactiveshell import InteractiveShell
if not InteractiveShell.initialized(): # Directly print objects. print(*objs) return
if transient is None: transient = {} if metadata is None: metadata={} if display_id: if display_id is True: display_id = _new_id() transient['display_id'] = display_id if kwargs.get('update') and 'display_id' not in transient: raise TypeError('display_id required for update_display') if transient: kwargs['transient'] = transient
if not objs and display_id: # if given no objects, but still a request for a display_id, # we assume the user wants to insert an empty output that # can be updated later objs = [{}] raw = True
if not raw: format = InteractiveShell.instance().display_formatter.format
if clear: clear_output(wait=True)
for obj in objs: if raw: publish_display_data(data=obj, metadata=metadata, **kwargs) else: format_dict, md_dict = format(obj, include=include, exclude=exclude) if not format_dict: # nothing to display (e.g. _ipython_display_ took over) continue if metadata: # kwarg-specified metadata gets precedence _merge(md_dict, metadata) publish_display_data(data=format_dict, metadata=md_dict, **kwargs) if display_id: return DisplayHandle(display_id)
# use * for keyword-only display_id argdef update_display(obj, *, display_id, **kwargs): """Update an existing display by id
Parameters ---------- obj The object with which to update the display display_id : keyword-only The id of the display to update
See Also -------- :func:`display` """ kwargs['update'] = True display(obj, display_id=display_id, **kwargs)
class DisplayHandle: """A handle on an updatable display
Call `.update(obj)` to display a new object.
Call `.display(obj`) to add a new instance of this display, and update existing instances.
See Also --------
:func:`display`, :func:`update_display`
"""
def __init__(self, display_id=None): if display_id is None: display_id = _new_id() self.display_id = display_id
def __repr__(self): return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
def display(self, obj, **kwargs): """Make a new display with my id, updating existing instances.
Parameters ---------- obj object to display **kwargs additional keyword arguments passed to display """ display(obj, display_id=self.display_id, **kwargs)
def update(self, obj, **kwargs): """Update existing displays with my id
Parameters ---------- obj object to display **kwargs additional keyword arguments passed to update_display """ update_display(obj, display_id=self.display_id, **kwargs)
def clear_output(wait=False): """Clear the output of the current cell receiving output.
Parameters ---------- wait : bool [default: false] Wait to clear the output until new output is available to replace it.""" from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): InteractiveShell.instance().display_pub.clear_output(wait) else: print('\033[2K\r', end='') sys.stdout.flush() print('\033[2K\r', end='') sys.stderr.flush()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# encoding: utf-8"""A context manager for handling sys.displayhook.
Authors:
* Robert Kern* Brian Granger"""
#-----------------------------------------------------------------------------# Copyright (C) 2008-2011 The IPython Development Team## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------
import sys
from traitlets.config.configurable import Configurablefrom traitlets import Any
#-----------------------------------------------------------------------------# Classes and functions#-----------------------------------------------------------------------------
class DisplayTrap(Configurable): """Object to manage sys.displayhook.
This came from IPython.core.kernel.display_hook, but is simplified (no callbacks or formatters) until more of the core is refactored. """
hook = Any()
def __init__(self, hook=None): super(DisplayTrap, self).__init__(hook=hook, config=None) self.old_hook = None # We define this to track if a single BuiltinTrap is nested. # Only turn off the trap when the outermost call to __exit__ is made. self._nested_level = 0
def __enter__(self): if self._nested_level == 0: self.set() self._nested_level += 1 return self
def __exit__(self, type, value, traceback): if self._nested_level == 1: self.unset() self._nested_level -= 1 # Returning False will cause exceptions to propagate return False
@property def is_active(self) -> bool: return self._nested_level != 0
def set(self): """Set the hook.""" if sys.displayhook is not self.hook: self.old_hook = sys.displayhook sys.displayhook = self.hook
def unset(self): """Unset the hook.""" sys.displayhook = self.old_hook
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346# -*- coding: utf-8 -*-"""Displayhook for IPython.
This defines a callable class that IPython uses for `sys.displayhook`."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import builtins as builtin_modimport sysimport io as _ioimport tokenize
from traitlets.config.configurable import Configurablefrom traitlets import Instance, Floatfrom warnings import warn
from .history import HistoryOutput
# TODO: Move the various attributes (cache_size, [others now moved]). Some# of these are also attributes of InteractiveShell. They should be on ONE object# only and the other objects should ask that one object for their values.
class DisplayHook(Configurable): """The custom IPython displayhook to replace sys.displayhook.
This class does many things, but the basic idea is that it is a callable that gets called anytime user code returns a value. """
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) exec_result = Instance('IPython.core.interactiveshell.ExecutionResult', allow_none=True) cull_fraction = Float(0.2)
def __init__(self, shell=None, cache_size=1000, **kwargs): super(DisplayHook, self).__init__(shell=shell, **kwargs) self._is_active = False cache_size_min = 3 if cache_size <= 0: self.do_full_cache = 0 cache_size = 0 elif cache_size < cache_size_min: self.do_full_cache = 0 cache_size = 0 warn('caching was disabled (min value for cache size is %s).' % cache_size_min,stacklevel=3) else: self.do_full_cache = 1
self.cache_size = cache_size
# we need a reference to the user-level namespace self.shell = shell
self._,self.__,self.___ = '','',''
# these are deliberately global: to_user_ns = {'_':self._,'__':self.__,'___':self.___} self.shell.user_ns.update(to_user_ns)
@property def prompt_count(self): return self.shell.execution_count - 1
#------------------------------------------------------------------------- # Methods used in __call__. Override these methods to modify the behavior # of the displayhook. #-------------------------------------------------------------------------
def check_for_underscore(self): """Check if the user has set the '_' variable by hand.""" # If something injected a '_' variable in __builtin__, delete # ipython's automatic one so we don't clobber that. gettext() in # particular uses _, so we need to stay away from it. if '_' in builtin_mod.__dict__: try: user_value = self.shell.user_ns['_'] if user_value is not self._: return del self.shell.user_ns['_'] except KeyError: pass
def quiet(self): """Should we silence the display hook because of ';'?""" # do not print output if input ends in ';'
try: cell = self.shell.history_manager.input_hist_parsed[-1] except IndexError: # some uses of ipshellembed may fail here return False
return self.semicolon_at_end_of_expression(cell)
@staticmethod def semicolon_at_end_of_expression(expression): """Parse Python expression and detects whether last token is ';'"""
sio = _io.StringIO(expression) tokens = list(tokenize.generate_tokens(sio.readline))
for token in reversed(tokens): if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): continue if (token[0] == tokenize.OP) and (token[1] == ';'): return True else: return False
def start_displayhook(self): """Start the displayhook, initializing resources.""" self._is_active = True
@property def is_active(self): return self._is_active
def write_output_prompt(self): """Write the output prompt.
The default implementation simply writes the prompt to ``sys.stdout``. """ # Use write, not print which adds an extra space. sys.stdout.write(self.shell.separate_out) outprompt = 'Out[{}]: '.format(self.shell.execution_count - 1) if self.do_full_cache: sys.stdout.write(outprompt)
def compute_format_data(self, result): """Compute format data of the object to be displayed.
The format data is a generalization of the :func:`repr` of an object. In the default implementation the format data is a :class:`dict` of key value pair where the keys are valid MIME types and the values are JSON'able data structure containing the raw data for that MIME type. It is up to frontends to determine pick a MIME to to use and display that data in an appropriate manner.
This method only computes the format data for the object and should NOT actually print or write that to a stream.
Parameters ---------- result : object The Python object passed to the display hook, whose format will be computed.
Returns ------- (format_dict, md_dict) : dict format_dict is a :class:`dict` whose keys are valid MIME types and values are JSON'able raw data for that MIME type. It is recommended that all return values of this should always include the "text/plain" MIME type representation of the object. md_dict is a :class:`dict` with the same MIME type keys of metadata associated with each output.
""" return self.shell.display_formatter.format(result)
# This can be set to True by the write_output_prompt method in a subclass prompt_end_newline = False
def write_format_data(self, format_dict, md_dict=None) -> None: """Write the format data dict to the frontend.
This default version of this method simply writes the plain text representation of the object to ``sys.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends.
Parameters ---------- format_dict : dict The format dict for the object passed to `sys.displayhook`. md_dict : dict (optional) The metadata dict to be associated with the display data. """ if 'text/plain' not in format_dict: # nothing to do return # We want to print because we want to always make sure we have a # newline, even if all the prompt separators are ''. This is the # standard IPython behavior. result_repr = format_dict['text/plain'] if '\n' in result_repr: # So that multi-line strings line up with the left column of # the screen, instead of having the output prompt mess up # their first line. # We use the prompt template instead of the expanded prompt # because the expansion may add ANSI escapes that will interfere # with our ability to determine whether or not we should add # a newline. if not self.prompt_end_newline: # But avoid extraneous empty lines. result_repr = '\n' + result_repr
try: print(result_repr) except UnicodeEncodeError: # If a character is not supported by the terminal encoding replace # it with its \u or \x representation print(result_repr.encode(sys.stdout.encoding,'backslashreplace').decode(sys.stdout.encoding))
def update_user_ns(self, result): """Update user_ns with various things like _, __, _1, etc."""
# Avoid recursive reference when displaying _oh/Out if self.cache_size and result is not self.shell.user_ns['_oh']: if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: self.cull_cache()
# Don't overwrite '_' and friends if '_' is in __builtin__ # (otherwise we cause buggy behavior for things like gettext). and # do not overwrite _, __ or ___ if one of these has been assigned # by the user. update_unders = True for unders in ['_'*i for i in range(1,4)]: if unders not in self.shell.user_ns: continue if getattr(self, unders) is not self.shell.user_ns.get(unders): update_unders = False
self.___ = self.__ self.__ = self._ self._ = result
if ('_' not in builtin_mod.__dict__) and (update_unders): self.shell.push({'_':self._, '__':self.__, '___':self.___}, interactive=False)
# hackish access to top-level namespace to create _1,_2... dynamically to_main = {} if self.do_full_cache: new_result = '_%s' % self.prompt_count to_main[new_result] = result self.shell.push(to_main, interactive=False) self.shell.user_ns['_oh'][self.prompt_count] = result
def fill_exec_result(self, result): if self.exec_result is not None: self.exec_result.result = result
def log_output(self, format_dict): """Log the output.""" self.shell.history_manager.outputs[self.prompt_count].append( HistoryOutput(output_type="execute_result", bundle=format_dict) ) if "text/plain" not in format_dict: # nothing to do return if self.shell.logger.log_output: self.shell.logger.log_write(format_dict['text/plain'], 'output') self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ format_dict['text/plain']
def finish_displayhook(self): """Finish up all displayhook activities.""" sys.stdout.write(self.shell.separate_out2) sys.stdout.flush() self._is_active = False
def __call__(self, result=None): """Printing with history cache management.
This is invoked every time the interpreter needs to print, and is activated by setting the variable sys.displayhook to it. """ self.check_for_underscore() if result is not None and not self.quiet(): self.start_displayhook() self.write_output_prompt() format_dict, md_dict = self.compute_format_data(result) self.update_user_ns(result) self.fill_exec_result(result) if format_dict: self.write_format_data(format_dict, md_dict) self.log_output(format_dict) self.finish_displayhook()
def cull_cache(self): """Output cache is full, cull the oldest entries""" oh = self.shell.user_ns.get('_oh', {}) sz = len(oh) cull_count = max(int(sz * self.cull_fraction), 2) warn('Output cache limit (currently {sz} entries) hit.\n' 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
for i, n in enumerate(sorted(oh)): if i >= cull_count: break self.shell.user_ns.pop('_%i' % n, None) oh.pop(n, None)
def flush(self): if not self.do_full_cache: raise ValueError("You shouldn't have reached the cache flush " "if full caching is not enabled!") # delete auto-generated vars from global namespace
for n in range(1,self.prompt_count + 1): key = '_'+repr(n) try: del self.shell.user_ns_hidden[key] except KeyError: pass try: del self.shell.user_ns[key] except KeyError: pass # In some embedded circumstances, the user_ns doesn't have the # '_oh' key set up. oh = self.shell.user_ns.get('_oh', None) if oh is not None: oh.clear()
# Release our own references to objects: self._, self.__, self.___ = '', '', ''
if '_' not in builtin_mod.__dict__: self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) import gc # TODO: Is this really needed? # IronPython blocks here forever if sys.platform != "cli": gc.collect()
class CapturingDisplayHook: def __init__(self, shell, outputs=None): self.shell = shell if outputs is None: outputs = [] self.outputs = outputs
def __call__(self, result=None): if result is None: return format_dict, md_dict = self.shell.display_formatter.format(result) self.outputs.append({ 'data': format_dict, 'metadata': md_dict })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445import inspectimport linecacheimport sysfrom collections.abc import Sequencefrom types import TracebackTypefrom typing import Any, Optionalfrom collections.abc import Callable
import stack_datafrom pygments.formatters.terminal256 import Terminal256Formatterfrom pygments.token import Token
from IPython.utils.PyColorize import Theme, TokenStream, theme_tablefrom IPython.utils.terminal import get_terminal_size
from .tbtools import ( FrameInfo, TBTools, _safe_string, _tokens_filename, eqrepr, get_line_number_of_frame, nullrepr,)
INDENT_SIZE = 8
def _format_traceback_lines( lines: list[stack_data.Line], theme: Theme, has_colors: bool, lvals_toks: list[TokenStream],) -> TokenStream: """ Format tracebacks lines with pointing arrow, leading numbers, this assumes the stack have been extracted using stackdata.
Parameters ---------- lines : list[Line] """ numbers_width = INDENT_SIZE - 1 tokens: TokenStream = [(Token, "\n")]
for stack_line in lines: if stack_line is stack_data.LINE_GAP: toks = [(Token.LinenoEm, " (...)")] tokens.extend(toks) continue
lineno = stack_line.lineno line = stack_line.render(pygmented=has_colors).rstrip("\n") + "\n" if stack_line.is_current: # This is the line with the error pad = numbers_width - len(str(lineno)) toks = [ (Token.Prompt, theme.make_arrow(3)), (Token, " "), (Token, line), ] else: # num = "%*s" % (numbers_width, lineno) toks = [ # (Token.LinenoEm, str(num)), (Token, "..."), (Token, " "), (Token, line), ]
tokens.extend(toks) if lvals_toks and stack_line.is_current: for lv in lvals_toks: tokens.append((Token, " " * INDENT_SIZE)) tokens.extend(lv) tokens.append((Token, "\n")) # strip the last newline tokens = tokens[:-1]
return tokens
class DocTB(TBTools): """
A stripped down version of Verbose TB, simplified to not have too much information when running doctests
"""
tb_highlight = "" tb_highlight_style = "default" tb_offset: int long_header: bool include_vars: bool
_mode: str
def __init__( self, # TODO: no default ? theme_name: str = "linux", call_pdb: bool = False, ostream: Any = None, tb_offset: int = 0, long_header: bool = False, include_vars: bool = True, check_cache: Callable[[], None] | None = None, debugger_cls: type | None = None, ): """Specify traceback offset, headers and color scheme.
Define how many frames to drop from the tracebacks. Calling it with tb_offset=1 allows use of this handler in interpreters which will have their own code at the top of the traceback (VerboseTB will first remove that frame before printing the traceback info).""" assert isinstance(theme_name, str) super().__init__( theme_name=theme_name, call_pdb=call_pdb, ostream=ostream, debugger_cls=debugger_cls, ) self.tb_offset = tb_offset self.long_header = long_header self.include_vars = include_vars # By default we use linecache.checkcache, but the user can provide a # different check_cache implementation. This was formerly used by the # IPython kernel for interactive code, but is no longer necessary. if check_cache is None: check_cache = linecache.checkcache self.check_cache = check_cache
self.skip_hidden = True
def format_record(self, frame_info: FrameInfo) -> str: """Format a single stack frame""" assert isinstance(frame_info, FrameInfo)
if isinstance(frame_info._sd, stack_data.RepeatedFrames): return theme_table[self._theme_name].format( [ (Token, " "), ( Token.ExcName, "[... skipping similar frames: %s]" % frame_info.description, ), (Token, "\n"), ] )
indent: str = " " * INDENT_SIZE
assert isinstance(frame_info.lineno, int) args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame) if frame_info.executing is not None: func = frame_info.executing.code_qualname() else: func = "?" if func == "<module>": call = "" else: # Decide whether to include variable details or not var_repr = eqrepr if self.include_vars else nullrepr try: scope = inspect.formatargvalues( args, varargs, varkw, locals_, formatvalue=var_repr ) assert isinstance(scope, str) call = theme_table[self._theme_name].format( [(Token, "in "), (Token.VName, func), (Token.ValEm, scope)] ) except KeyError: # This happens in situations like errors inside generator # expressions, where local variables are listed in the # line, but can't be extracted from the frame. I'm not # 100% sure this isn't actually a bug in inspect itself, # but since there's no info for us to compute with, the # best we can do is report the failure and move on. Here # we must *not* call any traceback construction again, # because that would mess up use of %debug later on. So we # simply report the failure and move on. The only # limitation will be that this frame won't have locals # listed in the call signature. Quite subtle problem... # I can't think of a good way to validate this in a unit # test, but running a script consisting of: # dict( (k,v.strip()) for (k,v) in range(10) ) # will illustrate the error, if this exception catch is # disabled. call = theme_table[self._theme_name].format( [ (Token, "in "), (Token.VName, func), (Token.ValEm, "(***failed resolving arguments***)"), ] )
lvals_toks: list[TokenStream] = [] if self.include_vars: try: # we likely want to fix stackdata at some point, but # still need a workaround. fibp = frame_info.variables_in_executing_piece for var in fibp: lvals_toks.append( [ (Token, var.name), (Token, " "), (Token.ValEm, "= "), (Token.ValEm, repr(var.value)), ] ) except Exception: lvals_toks.append( [ ( Token, "Exception trying to inspect frame. No more locals available.", ), ] )
assert frame_info._sd is not None result = theme_table[self._theme_name].format( _tokens_filename(True, frame_info.filename, lineno=frame_info.lineno) ) result += ", " if call else "" result += f"{call}\n" result += theme_table[self._theme_name].format( _format_traceback_lines( frame_info.lines, theme_table[self._theme_name], self.has_colors, lvals_toks, ) ) return result
def prepare_header(self, etype: str) -> str: width = min(75, get_terminal_size()[0]) head = theme_table[self._theme_name].format( [ ( Token, "Traceback (most recent call last):", ), (Token, " "), ] )
return head
def format_exception(self, etype: Any, evalue: Any) -> Any: # Get (safely) a string form of the exception info try: etype_str, evalue_str = map(str, (etype, evalue)) except: # User exception is improperly defined. etype, evalue = str, sys.exc_info()[:2] etype_str, evalue_str = map(str, (etype, evalue))
# PEP-678 notes notes = getattr(evalue, "__notes__", []) if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)): notes = [_safe_string(notes, "__notes__", func=repr)]
# ... and format it return [ theme_table[self._theme_name].format( [(Token.ExcName, etype_str), (Token, ": "), (Token, evalue_str)] ), *( theme_table[self._theme_name].format([(Token, _safe_string(n, "note"))]) for n in notes ), ]
def format_exception_as_a_whole( self, etype: type, evalue: Optional[BaseException], etb: Optional[TracebackType], context: int, tb_offset: Optional[int], ) -> list[list[str]]: """Formats the header, traceback and exception message for a single exception.
This may be called multiple times by Python 3 exception chaining (PEP 3134). """ # some locals orig_etype = etype try: etype = etype.__name__ # type: ignore[assignment] except AttributeError: pass
tb_offset = self.tb_offset if tb_offset is None else tb_offset assert isinstance(tb_offset, int) head = self.prepare_header(str(etype)) assert context == 1, context records = self.get_records(etb, context, tb_offset) if etb else []
frames = [] skipped = 0 nskipped = len(records) - 1 frames.append(self.format_record(records[0])) if nskipped: frames.append( theme_table[self._theme_name].format( [ (Token, "\n"), (Token, " "), (Token, "[... %s skipped frames]" % nskipped), (Token, "\n"), (Token, "\n"), ] ) )
formatted_exception = self.format_exception(etype, evalue) return [[head] + frames + formatted_exception]
def get_records(self, etb: TracebackType, context: int, tb_offset: int) -> Any: assert context == 1, context assert etb is not None context = context - 1 after = context // 2 before = context - after if self.has_colors: base_style = theme_table[self._theme_name].as_pygments_style() style = stack_data.style_with_executing_node(base_style, self.tb_highlight) formatter = Terminal256Formatter(style=style) else: formatter = None options = stack_data.Options( before=before, after=after, pygments_formatter=formatter, )
# Let's estimate the amount of code we will have to parse/highlight. cf: Optional[TracebackType] = etb max_len = 0 tbs = [] while cf is not None: try: mod = inspect.getmodule(cf.tb_frame) if mod is not None: mod_name = mod.__name__ root_name, *_ = mod_name.split(".") if root_name == "IPython": cf = cf.tb_next continue max_len = get_line_number_of_frame(cf.tb_frame)
except OSError: max_len = 0 max_len = max(max_len, max_len) tbs.append(cf) cf = getattr(cf, "tb_next", None)
res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:] res2 = [FrameInfo._from_stack_data_FrameInfo(r) for r in res] return res2
def structured_traceback( self, etype: type, evalue: Optional[BaseException], etb: Optional[TracebackType] = None, tb_offset: Optional[int] = None, context: int = 1, ) -> list[str]: """Return a nice text document describing the traceback.""" assert context > 0 assert context == 1, context formatted_exceptions: list[list[str]] = self.format_exception_as_a_whole( etype, evalue, etb, context, tb_offset )
termsize = min(75, get_terminal_size()[0]) theme = theme_table[self._theme_name] structured_traceback_parts: list[str] = [] chained_exceptions_tb_offset = 0 lines_of_context = 3 exception = self.get_parts_of_chained_exception(evalue) if exception: assert evalue is not None formatted_exceptions += self.prepare_chained_exception_message( evalue.__cause__ ) etype, evalue, etb = exception else: evalue = None chained_exc_ids = set() while evalue: formatted_exceptions += self.format_exception_as_a_whole( etype, evalue, etb, lines_of_context, chained_exceptions_tb_offset ) exception = self.get_parts_of_chained_exception(evalue)
if exception and id(exception[1]) not in chained_exc_ids: chained_exc_ids.add( id(exception[1]) ) # trace exception to avoid infinite 'cause' loop formatted_exceptions += self.prepare_chained_exception_message( evalue.__cause__ ) etype, evalue, etb = exception else: evalue = None
# we want to see exceptions in a reversed order: # the first exception should be on top for fx in reversed(formatted_exceptions): structured_traceback_parts += fx
return structured_traceback_parts
def debugger(self, force: bool = False) -> None: raise RuntimeError("canot rundebugger in Docs mode")
def handler(self, info: tuple[Any, Any, Any] | None = None) -> None: (etype, evalue, etb) = info or sys.exc_info() self.tb = etb ostream = self.ostream ostream.flush() ostream.write(self.text(etype, evalue, etb)) # type:ignore[arg-type] ostream.write("\n") ostream.flush()
# Changed so an instance can just be called as VerboseTB_inst() and print # out the right info on its own. def __call__(self, etype: Any = None, evalue: Any = None, etb: Any = None) -> None: """This hook can replace sys.excepthook (for Python 2.1 or higher).""" if etb is None: self.handler() else: self.handler((etype, evalue, etb)) try: self.debugger() except KeyboardInterrupt: print("\nKeyboardInterrupt")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Infrastructure for registering and firing callbacks on application events.
Unlike :mod:`IPython.core.hooks`, which lets end users set single functions tobe called at specific times, or a collection of alternative methods to try,callbacks are designed to be used by extension authors. A number of callbackscan be registered for the same event without needing to be aware of one another.
The functions defined in this module are no-ops indicating the names of availableevents and the arguments which will be passed to them.
.. note::
This API is experimental in IPython 2.0, and may be revised in future versions."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Iterable
if TYPE_CHECKING: from IPython.core.interactiveshell import InteractiveShell
class EventManager: """Manage a collection of events and a sequence of callbacks for each. This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell` instances as an ``events`` attribute. .. note::
This API is experimental in IPython 2.0, and may be revised in future versions. """
def __init__( self, shell: InteractiveShell, available_events: Iterable[str], print_on_error: bool = True, ) -> None: """Initialise the :class:`CallbackManager`.
Parameters ---------- shell The :class:`~IPython.core.interactiveshell.InteractiveShell` instance available_events An iterable of names for callback events. print_on_error: A boolean flag to set whether the EventManager will print a warning which a event errors. """ self.shell = shell self.callbacks: dict[str, list[Callable[..., Any]]] = { n: [] for n in available_events } self.print_on_error = print_on_error def register(self, event: str, function: Callable[..., Any]) -> None: """Register a new event callback.
Parameters ---------- event : str The event for which to register this callback. function : callable A function to be called on the given event. It should take the same parameters as the appropriate callback prototype.
Raises ------ TypeError If ``function`` is not callable. KeyError If ``event`` is not one of the known events. """ if not callable(function): raise TypeError('Need a callable, got %r' % function) if function not in self.callbacks[event]: self.callbacks[event].append(function) def unregister(self, event: str, function: Callable[..., Any]) -> None: """Remove a callback from the given event.""" if function in self.callbacks[event]: return self.callbacks[event].remove(function)
raise ValueError('Function {!r} is not registered as a {} callback'.format(function, event))
def trigger(self, event: str, *args: Any, **kwargs: Any) -> None: """Call callbacks for ``event``.
Any additional arguments are passed to all callbacks registered for this event. Exceptions raised by callbacks are caught, and a message printed. """ for func in self.callbacks[event][:]: try: func(*args, **kwargs) except (Exception, KeyboardInterrupt): if self.print_on_error: print( "Error in callback {} (for {}), with arguments args {},kwargs {}:".format( func, event, args, kwargs ) ) self.shell.showtraceback()
# event_name -> prototype mappingavailable_events: dict[str, Callable[..., Any]] = {}
def _define_event(callback_function: Callable[..., Any]) -> Callable[..., Any]: available_events[callback_function.__name__] = callback_function return callback_function
# ------------------------------------------------------------------------------# Callback prototypes## No-op functions which describe the names of available events and the# signatures of callbacks for those events.# ------------------------------------------------------------------------------
@_define_eventdef pre_execute() -> None: """Fires before code is executed in response to user/frontend action.
This includes comm and widget messages and silent execution, as well as user code cells. """ pass
@_define_eventdef pre_run_cell(info: Any) -> None: """Fires before user-entered code runs.
Parameters ---------- info : :class:`~IPython.core.interactiveshell.ExecutionInfo` An object containing information used for the code execution. """ pass
@_define_eventdef post_execute() -> None: """Fires after code is executed in response to user/frontend action.
This includes comm and widget messages and silent execution, as well as user code cells. """ pass
@_define_eventdef post_run_cell(result: Any) -> None: """Fires after user-entered code runs.
Parameters ---------- result : :class:`~IPython.core.interactiveshell.ExecutionResult` The object which will be returned as the execution result. """ pass
@_define_eventdef shell_initialized(ip: InteractiveShell) -> None: """Fires after initialisation of :class:`~IPython.core.interactiveshell.InteractiveShell`.
This is before extensions and startup scripts are loaded, so it can only be set by subclassing.
Parameters ---------- ip : :class:`~IPython.core.interactiveshell.InteractiveShell` The newly initialised shell. """ pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090# -*- coding: utf-8 -*-"""Display formatters.
This module defines the base instances in order to implement customformatters/mimetypesgot objects:
As we want to see internal IPython working we are going to use the followingfunction to diaply objects instead of the normal print or display method:
>>> ip = get_ipython() >>> ip.display_formatter.format(...) ({'text/plain': 'Ellipsis'}, {})
This return a tuple with the mimebumdle for the current object, and theassociated metadata.
We can now define our own formatter and register it:
>>> from IPython.core.formatters import BaseFormatter, FormatterABC
>>> class LLMFormatter(BaseFormatter): ... ... format_type = 'x-vendor/llm' ... print_method = '_repr_llm_' ... _return_type = (dict, str)
>>> llm_formatter = LLMFormatter(parent=ip.display_formatter)
>>> ip.display_formatter.formatters[LLMFormatter.format_type] = llm_formatter
Now any class that define `_repr_llm_` will return a x-vendor/llm as part ofit's display data:
>>> class A: ... ... def _repr_llm_(self, *kwargs): ... return 'This a A' ...
>>> ip.display_formatter.format(A()) ({'text/plain': '<IPython.core.formatters.A at ...>', 'x-vendor/llm': 'This a A'}, {})
As usual, you can register methods for third party types (see:ref:`third_party_formatting`)
>>> def llm_int(obj): ... return 'This is the integer %s, in between %s and %s'%(obj, obj-1, obj+1)
>>> llm_formatter.for_type(int, llm_int)
>>> ip.display_formatter.format(42) ({'text/plain': '42', 'x-vendor/llm': 'This is the integer 42, in between 41 and 43'}, {})
Inheritance diagram:
.. inheritance-diagram:: IPython.core.formatters :parts: 3"""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import abcimport sysimport tracebackimport warningsfrom io import StringIO
from decorator import decorator
from traitlets.config.configurable import Configurablefrom .getipython import get_ipythonfrom ..utils.sentinel import Sentinelfrom ..utils.dir2 import get_real_methodfrom ..lib import prettyfrom traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ForwardDeclaredInstance, default, observe,)
from typing import Any
class DisplayFormatter(Configurable):
active_types = List(Unicode(), help="""List of currently active mime-types to display. You can use this to set a white-list for formats to display.
Most users will not need to change this value. """, ).tag(config=True)
@default('active_types') def _active_types_default(self): return self.format_types
@observe('active_types') def _active_types_changed(self, change): for key, formatter in self.formatters.items(): if key in change['new']: formatter.enabled = True else: formatter.enabled = False
ipython_display_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
@default("ipython_display_formatter") def _default_formatter(self): return IPythonDisplayFormatter(parent=self)
mimebundle_formatter = ForwardDeclaredInstance("FormatterABC") # type: ignore
@default("mimebundle_formatter") def _default_mime_formatter(self): return MimeBundleFormatter(parent=self)
# A dict of formatter whose keys are format types (MIME types) and whose # values are subclasses of BaseFormatter. formatters = Dict()
@default("formatters") def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, MarkdownFormatter, SVGFormatter, PNGFormatter, PDFFormatter, JPEGFormatter, LatexFormatter, JSONFormatter, JavascriptFormatter ] d = {} for cls in formatter_classes: f = cls(parent=self) d[f.format_type] = f return d
def format(self, obj, include=None, exclude=None): """Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are usually implemented:
* text/plain * text/html * text/markdown * text/latex * application/json * application/javascript * application/pdf * image/png * image/jpeg * image/svg+xml
Parameters ---------- obj : object The Python object whose format data will be computed. include : list, tuple or set; optional A list of format type strings (MIME types) to include in the format data dict. If this is set *only* the format types included in this list will be computed. exclude : list, tuple or set; optional A list of format type string (MIME types) to exclude in the format data dict. If this is set all format types will be computed, except for those included in this argument. Mimetypes present in exclude will take precedence over the ones in include
Returns ------- (format_dict, metadata_dict) : tuple of two dicts format_dict is a dictionary of key/value pairs, one of 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.
metadata_dict is a dictionary of metadata about each mime-type output. Its keys will be a strict subset of the keys in format_dict.
Notes ----- If an object implement `_repr_mimebundle_` as well as various `_repr_*_`, the data returned by `_repr_mimebundle_` will take precedence and the corresponding `_repr_*_` for this mimetype will not be called.
""" format_dict = {} md_dict = {}
if self.ipython_display_formatter(obj): # object handled itself, don't proceed return {}, {}
format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
if format_dict or md_dict: if include: format_dict = {k:v for k,v in format_dict.items() if k in include} md_dict = {k:v for k,v in md_dict.items() if k in include} if exclude: format_dict = {k:v for k,v in format_dict.items() if k not in exclude} md_dict = {k:v for k,v in md_dict.items() if k not in exclude}
for format_type, formatter in self.formatters.items(): if format_type in format_dict: # already got it from mimebundle, maybe don't render again. # exception: manually registered per-mime renderer # check priority: # 1. user-registered per-mime formatter # 2. mime-bundle (user-registered or repr method) # 3. default per-mime formatter (e.g. repr method) try: formatter.lookup(obj) except KeyError: # no special formatter, use mime-bundle-provided value continue if include and format_type not in include: continue if exclude and format_type in exclude: continue
md = None try: data = formatter(obj) except: # FIXME: log the exception raise
# formatters can return raw data or (data, metadata) if isinstance(data, tuple) and len(data) == 2: data, md = data
if data is not None: format_dict[format_type] = data if md is not None: md_dict[format_type] = md return format_dict, md_dict
@property def format_types(self): """Return the format types (MIME types) of the active formatters.""" return list(self.formatters.keys())
#-----------------------------------------------------------------------------# Formatters for specific format types (text, html, svg, etc.)#-----------------------------------------------------------------------------
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
class FormatterWarning(UserWarning): """Warning class for errors in formatters"""
@decoratordef 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])
class FormatterABC(metaclass=abc.ABCMeta): """ Abstract base class for Formatters.
A formatter is a callable class that is responsible for computing the raw format data for a particular format type (MIME type). For example, an HTML formatter would have a format type of `text/html` and would return the HTML representation of the object when called. """
# The format type of the data returned, usually a MIME type. format_type = 'text/plain'
# Is the formatter enabled... enabled = True
@abc.abstractmethod def __call__(self, obj): """Return a JSON'able representation of the object.
If the object cannot be formatted by this formatter, warn and return None. """ return repr(obj)
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)
def _get_type(obj): """Return the type of an instance (old and new-style)""" return getattr(obj, '__class__', None) or type(obj)
_raise_key_error = Sentinel( "_raise_key_error", __name__, """Special value to raise a KeyError
Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`""",)
class BaseFormatter(Configurable): """A base formatter class that is configurable.
This formatter should usually be used as the base class of all formatters. It is a traited :class:`Configurable` class and includes an extensible API for users to determine how their objects are formatted. The following logic is used to find a function to format an given object.
1. The object is introspected to see if it has a method with the name :attr:`print_method`. If is does, that object is passed to that method for formatting. 2. If no print method is found, three internal dictionaries are consulted to find print method: :attr:`singleton_printers`, :attr:`type_printers` and :attr:`deferred_printers`.
Users should use these dictionaries to register functions that will be used to compute the format data for their objects (if those objects don't have the special print methods). The easiest way of using these dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` methods.
If no function/callable is found to compute the format data, :py:data:`None` is returned and this format type is not used. """
format_type = Unicode("text/plain") _return_type: Any = str
enabled = Bool(True).tag(config=True)
print_method = ObjectName('__repr__')
# The singleton printers. # Maps the IDs of the builtin singleton objects to the format functions. singleton_printers = Dict().tag(config=True)
# The type-specific printers. # Map type objects to the format functions. type_printers = Dict().tag(config=True)
# The deferred-import type-specific printers. # Map (modulename, classname) pairs to the format functions. deferred_printers = Dict().tag(config=True)
@catch_format_error def __call__(self, obj): """Compute the format for an object.""" if self.enabled: # lookup registered printer try: printer = self.lookup(obj) except KeyError: pass else: return printer(obj) # Finally look for special method names method = get_real_method(obj, self.print_method) if method is not None: return method() return None else: return None
def __contains__(self, typ): """map in to lookup_by_type""" try: self.lookup_by_type(typ) except KeyError: return False else: return True
def _check_return(self, r, obj): """Check that a return value is appropriate
Return the value if so, None otherwise, warning if invalid. """ if r is None or isinstance(r, self._return_type) or \ (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): return r else: warnings.warn( "%s formatter returned invalid type %s (expected %s) for object: %s" % \ (self.format_type, type(r), self._return_type, _safe_repr(obj)), FormatterWarning )
def lookup(self, obj): """Look up the formatter for a given instance.
Parameters ---------- obj : object instance
Returns ------- f : callable The registered formatting callable for the type.
Raises ------ KeyError if the type has not been registered. """ # look for singleton first obj_id = id(obj) if obj_id in self.singleton_printers: return self.singleton_printers[obj_id] # then lookup by type return self.lookup_by_type(_get_type(obj))
def lookup_by_type(self, typ): """Look up the registered formatter for a type.
Parameters ---------- typ : type or '__module__.__name__' string for a type
Returns ------- f : callable The registered formatting callable for the type.
Raises ------ KeyError if the type has not been registered. """ if isinstance(typ, str): typ_key = tuple(typ.rsplit('.',1)) if typ_key not in self.deferred_printers: # We may have it cached in the type map. We will have to # iterate over all of the types to check. for cls in self.type_printers: if _mod_name_key(cls) == typ_key: return self.type_printers[cls] else: return self.deferred_printers[typ_key] else: for cls in pretty._get_mro(typ): if cls in self.type_printers or self._in_deferred_types(cls): return self.type_printers[cls]
# If we have reached here, the lookup failed. raise KeyError("No registered printer for {0!r}".format(typ))
def for_type(self, typ, func=None): """Add a format function for a given type.
Parameters ---------- typ : type or '__module__.__name__' string for a type The class of the object that will be formatted using `func`.
func : callable A callable for computing the format data. `func` will be called with the object to be formatted, and will return the raw data in this formatter's format. Subclasses may use a different call signature for the `func` argument.
If `func` is None or not specified, there will be no change, only returning the current value.
Returns ------- oldfunc : callable The currently registered callable. If you are registering a new formatter, this will be the previous value (to enable restoring later). """ # if string given, interpret as 'pkg.module.class_name' if isinstance(typ, str): type_module, type_name = typ.rsplit('.', 1) return self.for_type_by_name(type_module, type_name, func)
try: oldfunc = self.lookup_by_type(typ) except KeyError: oldfunc = None
if func is not None: self.type_printers[typ] = func
return oldfunc
def for_type_by_name(self, type_module, type_name, func=None): """Add a format function for a type specified by the full dotted module and name of the type, rather than the type of the object.
Parameters ---------- type_module : str The full dotted name of the module the type is defined in, like ``numpy``.
type_name : str The name of the type (the class name), like ``dtype``
func : callable A callable for computing the format data. `func` will be called with the object to be formatted, and will return the raw data in this formatter's format. Subclasses may use a different call signature for the `func` argument.
If `func` is None or unspecified, there will be no change, only returning the current value.
Returns ------- oldfunc : callable The currently registered callable. If you are registering a new formatter, this will be the previous value (to enable restoring later). """ key = (type_module, type_name)
try: oldfunc = self.lookup_by_type("%s.%s" % key) except KeyError: oldfunc = None
if func is not None: self.deferred_printers[key] = func return oldfunc
def pop(self, typ, default=_raise_key_error): """Pop a formatter for the given type.
Parameters ---------- typ : type or '__module__.__name__' string for a type default : object value to be returned if no formatter is registered for typ.
Returns ------- obj : object The last registered object for the type.
Raises ------ KeyError if the type is not registered and default is not specified. """
if isinstance(typ, str): typ_key = tuple(typ.rsplit('.',1)) if typ_key not in self.deferred_printers: # We may have it cached in the type map. We will have to # iterate over all of the types to check. for cls in self.type_printers: if _mod_name_key(cls) == typ_key: old = self.type_printers.pop(cls) break else: old = default else: old = self.deferred_printers.pop(typ_key) else: if typ in self.type_printers: old = self.type_printers.pop(typ) else: old = self.deferred_printers.pop(_mod_name_key(typ), default) if old is _raise_key_error: raise KeyError("No registered value for {0!r}".format(typ)) return old
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry.
Successful matches will be moved to the regular type registry for future use. """ mod = getattr(cls, '__module__', None) name = getattr(cls, '__name__', None) key = (mod, name) if key in self.deferred_printers: # Move the printer over to the regular registry. printer = self.deferred_printers.pop(key) self.type_printers[cls] = printer return True return False
class PlainTextFormatter(BaseFormatter): """The default pretty-printer.
This uses :mod:`IPython.lib.pretty` to compute the format data of the object. If the object cannot be pretty printed, :func:`repr` is used. See the documentation of :mod:`IPython.lib.pretty` for details on how to write pretty printers. Here is a simple example::
def dtype_pprinter(obj, p, cycle): if cycle: return p.text('dtype(...)') if hasattr(obj, 'fields'): if obj.fields is None: p.text(repr(obj)) else: p.begin_group(7, 'dtype([') for i, field in enumerate(obj.descr): if i > 0: p.text(',') p.breakable() p.pretty(field) p.end_group(7, '])') """
# The format type of data returned. format_type = Unicode('text/plain')
# This subclass ignores this attribute as it always need to return # something. enabled = Bool(True).tag(config=False)
max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
Set to 0 to disable truncation. """, ).tag(config=True)
# Look for a _repr_pretty_ methods to use for pretty printing. print_method = ObjectName('_repr_pretty_')
# Whether to pretty-print or not. pprint = Bool(True).tag(config=True)
# Whether to be verbose or not. verbose = Bool(False).tag(config=True)
# The maximum width. max_width = Integer(79).tag(config=True)
# The newline character. newline = Unicode('\n').tag(config=True)
# format-string for pprinting floats float_format = Unicode('%r') # setter for float precision, either int or direct format-string float_precision = CUnicode('').tag(config=True)
@observe('float_precision') def _float_precision_changed(self, change): """float_precision changed, set float_format accordingly.
float_precision can be set by int or str. This will set float_format, after interpreting input. If numpy has been imported, numpy print precision will also be set.
integer `n` sets format to '%.nf', otherwise, format set directly.
An empty string returns to defaults (repr for float, 8 for numpy).
This parameter can be set via the '%precision' magic. """ new = change['new'] if '%' in new: # got explicit format string fmt = new try: fmt%3.14159 except Exception as e: raise ValueError("Precision must be int or format string, not %r"%new) from e elif new: # otherwise, should be an int try: i = int(new) assert i >= 0 except ValueError as e: raise ValueError("Precision must be int or format string, not %r"%new) from e except AssertionError as e: raise ValueError("int precision must be non-negative, not %r"%i) from e
fmt = '%%.%if'%i if 'numpy' in sys.modules: # set numpy precision if it has been imported import numpy numpy.set_printoptions(precision=i) else: # default back to repr fmt = '%r' if 'numpy' in sys.modules: import numpy # numpy default is 8 numpy.set_printoptions(precision=8) self.float_format = fmt
# Use the default pretty printers from IPython.lib.pretty. @default('singleton_printers') def _singleton_printers_default(self): return pretty._singleton_pprinters.copy()
@default('type_printers') def _type_printers_default(self): d = pretty._type_pprinters.copy() d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) # if NumPy is used, set precision for its float64 type if "numpy" in sys.modules: import numpy
d[numpy.float64] = lambda obj, p, cycle: p.text(self.float_format % obj) return d
@default('deferred_printers') def _deferred_printers_default(self): return pretty._deferred_type_pprinters.copy()
#### FormatterABC interface ####
@catch_format_error def __call__(self, obj): """Compute the pretty representation of the object.""" if not self.pprint: return repr(obj) else: stream = StringIO() printer = pretty.RepresentationPrinter(stream, self.verbose, self.max_width, self.newline, max_seq_length=self.max_seq_length, singleton_pprinters=self.singleton_printers, type_pprinters=self.type_printers, deferred_pprinters=self.deferred_printers) printer.pretty(obj) printer.flush() return stream.getvalue()
class HTMLFormatter(BaseFormatter): """An HTML formatter.
To define the callables that compute the HTML representation of your objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be a valid HTML snippet that could be injected into an existing DOM. It should *not* include the ```<html>`` or ```<body>`` tags. """ format_type = Unicode('text/html')
print_method = ObjectName('_repr_html_')
class MarkdownFormatter(BaseFormatter): """A Markdown formatter.
To define the callables that compute the Markdown representation of your objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be a valid Markdown. """ format_type = Unicode('text/markdown')
print_method = ObjectName('_repr_markdown_')
class SVGFormatter(BaseFormatter): """An SVG formatter.
To define the callables that compute the SVG representation of your objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be valid SVG enclosed in ```<svg>``` tags, that could be injected into an existing DOM. It should *not* include the ```<html>`` or ```<body>`` tags. """ format_type = Unicode('image/svg+xml')
print_method = ObjectName('_repr_svg_')
class PNGFormatter(BaseFormatter): """A PNG formatter.
To define the callables that compute the PNG representation of your objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be raw PNG data, *not* base64 encoded. """ format_type = Unicode('image/png')
print_method = ObjectName('_repr_png_')
_return_type = (bytes, str)
class JPEGFormatter(BaseFormatter): """A JPEG formatter.
To define the callables that compute the JPEG representation of your objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be raw JPEG data, *not* base64 encoded. """ format_type = Unicode('image/jpeg')
print_method = ObjectName('_repr_jpeg_')
_return_type = (bytes, str)
class LatexFormatter(BaseFormatter): """A LaTeX formatter.
To define the callables that compute the LaTeX representation of your objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be a valid LaTeX equation, enclosed in either ```$```, ```$$``` or another LaTeX equation environment. """ format_type = Unicode('text/latex')
print_method = ObjectName('_repr_latex_')
class JSONFormatter(BaseFormatter): """A JSON string formatter.
To define the callables that compute the JSONable representation of your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be a JSONable list or dict. JSON scalars (None, number, string) are not allowed, only dict or list containers. """ format_type = Unicode('application/json') _return_type = (list, dict)
print_method = ObjectName('_repr_json_')
def _check_return(self, r, obj): """Check that a return value is appropriate
Return the value if so, None otherwise, warning if invalid. """ if r is None: return md = None if isinstance(r, tuple): # unpack data, metadata tuple for type checking on first element r, md = r
assert not isinstance( r, str ), "JSON-as-string has been deprecated since IPython < 3"
if md is not None: # put the tuple back together r = (r, md) return super(JSONFormatter, self)._check_return(r, obj)
class JavascriptFormatter(BaseFormatter): """A Javascript formatter.
To define the callables that compute the Javascript representation of your objects, define a :meth:`_repr_javascript_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be valid Javascript code and should *not* be enclosed in ```<script>``` tags. """ format_type = Unicode('application/javascript')
print_method = ObjectName('_repr_javascript_')
class PDFFormatter(BaseFormatter): """A PDF formatter.
To define the callables that compute the PDF representation of your objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
The return value of this formatter should be raw PDF data, *not* base64 encoded. """ format_type = Unicode('application/pdf')
print_method = ObjectName('_repr_pdf_')
_return_type = (bytes, str)
class IPythonDisplayFormatter(BaseFormatter): """An escape-hatch Formatter for objects that know how to display themselves.
To define the callables that compute the representation of your objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this. Unlike mime-type displays, this method should not return anything, instead calling any appropriate display methods itself.
This display formatter has highest priority. If it fires, no other display formatter will be called.
Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types without registering a new Formatter.
IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types, so `_ipython_display_` should only be used for objects that require unusual display patterns, such as multiple display calls. """ print_method = ObjectName('_ipython_display_') _return_type = (type(None), bool)
@catch_format_error def __call__(self, obj): """Compute the format for an object.""" if self.enabled: # lookup registered printer try: printer = self.lookup(obj) except KeyError: pass else: printer(obj) return True # Finally look for special method names method = get_real_method(obj, self.print_method) if method is not None: method() return True
class MimeBundleFormatter(BaseFormatter): """A Formatter for arbitrary mime-types.
Unlike other `_repr_<mimetype>_` methods, `_repr_mimebundle_` should return mime-bundle data, either the mime-keyed `data` dictionary or the tuple `(data, metadata)`. Any mime-type is valid.
To define the callables that compute the mime-bundle representation of your objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this.
.. versionadded:: 6.1 """ print_method = ObjectName('_repr_mimebundle_') _return_type = dict
def _check_return(self, r, obj): r = super(MimeBundleFormatter, self)._check_return(r, obj) # always return (data, metadata): if r is None: return {}, {} if not isinstance(r, tuple): return r, {} return r
@catch_format_error def __call__(self, obj, include=None, exclude=None): """Compute the format for an object.
Identical to parent's method but we pass extra parameters to the method.
Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in particular `include` and `exclude`. """ if self.enabled: # lookup registered printer try: printer = self.lookup(obj) except KeyError: pass else: return printer(obj) # Finally look for special method names method = get_real_method(obj, self.print_method)
if method is not None: return method(include=include, exclude=exclude) return None else: return None
FormatterABC.register(BaseFormatter)FormatterABC.register(PlainTextFormatter)FormatterABC.register(HTMLFormatter)FormatterABC.register(MarkdownFormatter)FormatterABC.register(SVGFormatter)FormatterABC.register(PNGFormatter)FormatterABC.register(PDFFormatter)FormatterABC.register(JPEGFormatter)FormatterABC.register(LatexFormatter)FormatterABC.register(JSONFormatter)FormatterABC.register(JavascriptFormatter)FormatterABC.register(IPythonDisplayFormatter)FormatterABC.register(MimeBundleFormatter)
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 )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158# encoding: utf-8"""An application for managing IPython history.
To be invoked as the `ipython history` subcommand."""
import sqlite3from pathlib import Path
from traitlets.config.application import Applicationfrom .application import BaseIPythonApplicationfrom traitlets import Bool, Int, Dictfrom ..utils.io import ask_yes_no
trim_hist_help = """Trim the IPython history database to the last 1000 entries.
This actually copies the last 1000 entries to a new database, and then replacesthe old file with the new. Use the `--keep=` argument to specify a numberother than 1000."""
clear_hist_help = """Clear the IPython history database, deleting all entries.
Because this is a destructive operation, IPython will prompt the user if theyreally want to do this. Passing a `-f` flag will force clearing without aprompt.
This is an handy alias to `ipython history trim --keep=0`"""
class HistoryTrim(BaseIPythonApplication): description = trim_hist_help
backup = Bool(False, help="Keep the old history file as history.sqlite.<N>").tag( config=True )
keep = Int(1000, help="Number of recent lines to keep in the database.").tag( config=True )
flags = Dict( # type: ignore dict(backup=({"HistoryTrim": {"backup": True}}, backup.help)) )
aliases = Dict(dict(keep="HistoryTrim.keep")) # type: ignore
def start(self): profile_dir = Path(self.profile_dir.location) hist_file = profile_dir / "history.sqlite" con = sqlite3.connect(hist_file)
# Grab the recent history from the current database. inputs = list(con.execute('SELECT session, line, source, source_raw FROM ' 'history ORDER BY session DESC, line DESC LIMIT ?', (self.keep+1,))) if len(inputs) <= self.keep: print("There are already at most %d entries in the history database." % self.keep) print("Not doing anything. Use --keep= argument to keep fewer entries") return
print("Trimming history to the most recent %d entries." % self.keep)
inputs.pop() # Remove the extra element we got to check the length. inputs.reverse() if inputs: first_session = inputs[0][0] outputs = list(con.execute('SELECT session, line, output FROM ' 'output_history WHERE session >= ?', (first_session,))) sessions = list(con.execute('SELECT session, start, end, num_cmds, remark FROM ' 'sessions WHERE session >= ?', (first_session,))) con.close()
# Create the new history database. new_hist_file = profile_dir / "history.sqlite.new" i = 0 while new_hist_file.exists(): # Make sure we don't interfere with an existing file. i += 1 new_hist_file = profile_dir / ("history.sqlite.new" + str(i)) new_db = sqlite3.connect(new_hist_file) new_db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer primary key autoincrement, start timestamp, end timestamp, num_cmds integer, remark text)""") new_db.execute("""CREATE TABLE IF NOT EXISTS history (session integer, line integer, source text, source_raw text, PRIMARY KEY (session, line))""") new_db.execute("""CREATE TABLE IF NOT EXISTS output_history (session integer, line integer, output text, PRIMARY KEY (session, line))""") new_db.commit()
if inputs: with new_db: # Add the recent history into the new database. new_db.executemany('insert into sessions values (?,?,?,?,?)', sessions) new_db.executemany('insert into history values (?,?,?,?)', inputs) new_db.executemany('insert into output_history values (?,?,?)', outputs) new_db.close()
if self.backup: i = 1 backup_hist_file = profile_dir / ("history.sqlite.old.%d" % i) while backup_hist_file.exists(): i += 1 backup_hist_file = profile_dir / ("history.sqlite.old.%d" % i) hist_file.rename(backup_hist_file) print("Backed up longer history file to", backup_hist_file) else: hist_file.unlink()
new_hist_file.rename(hist_file)
class HistoryClear(HistoryTrim): description = clear_hist_help keep = Int(0, help="Number of recent lines to keep in the database.")
force = Bool(False, help="Don't prompt user for confirmation").tag(config=True)
flags = Dict( # type: ignore dict( force=({"HistoryClear": {"force": True}}, force.help), f=({"HistoryTrim": {"force": True}}, force.help), ) ) aliases = Dict() # type: ignore
def start(self): if self.force or ask_yes_no( "Really delete all ipython history? ", default="no", interrupt="no" ): HistoryTrim.start(self)
class HistoryApp(Application): name = "ipython-history" description = "Manage the IPython history database."
subcommands = Dict(dict( trim = (HistoryTrim, HistoryTrim.description.splitlines()[0]), clear = (HistoryClear, HistoryClear.description.splitlines()[0]), ))
def start(self): if self.subapp is None: print( "No subcommand specified. Must specify one of: " + ", ".join(map(repr, self.subcommands)) + ".\n" ) self.print_description() self.print_subcommands() self.exit(1) else: return self.subapp.start()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898"""Input transformer machinery to support IPython special syntax.
This includes the machinery to recognise and transform ``%magic`` commands,``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
Added: IPython 7.0. Replaces inputsplitter and inputtransformer which weredeprecated in 7.0 and removed in 9.0"""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import astfrom codeop import CommandCompiler, Compileimport reimport sysimport tokenizefrom typing import List, Tuple, Optional, Anyimport warningsfrom textwrap import dedent
from IPython.utils import tokenutil
_indent_re = re.compile(r'^[ \t]+')
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
def leading_indent(lines): """Remove leading indentation.
Removes the minimum common leading indentation from all lines. """ if not lines: return lines return dedent("".join(lines)).splitlines(keepends=True)
class PromptStripper: """Remove matching input prompts from a block of input.
Parameters ---------- prompt_re : regular expression A regular expression matching any input prompt (including continuation, e.g. ``...``) 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. """ def __init__(self, prompt_re, initial_re=None, *, doctest=False): self.prompt_re = prompt_re self.initial_re = initial_re or prompt_re self.doctest = doctest if doctest: # Doctest/xdoctest prompts may be indented (e.g. " >>>"). # We only treat "..." as a continuation prompt when the same pasted # block contains at least one ">>>" line, to avoid ambiguity with the # Python Ellipsis literal. self._doctest_initial_re = re.compile(r'^\s*>>>') self._doctest_ps1_re = re.compile(r'^\s*>>>\s?') self._doctest_ps2_re = re.compile(r'^\s*\.\.\.\s?')
# Very small state machine to detect triple-quoted strings in the # *same* input block (e.g. user typed """ then pasted doctest). # We preserve literal >>> / ... inside triple-quoted strings. self._triple_quote_re = re.compile(r"(?<!\\)(\"\"\"|''')")
def _triple_quote_mask(self, lines: List[str]) -> List[bool]: """ Return a boolean mask: True if the corresponding line is considered inside a triple-quoted string literal.
This is intentionally heuristic (fast + good enough for paste handling). """ mask: List[bool] = [] in_triple: str | None = None # either ''' or """ for line in lines: mask.append(in_triple is not None) # Toggle state for each occurrence of """ or ''' in the line. for m in self._triple_quote_re.finditer(line): q = m.group(1) if in_triple is None: in_triple = q mask[-1] = True # current line is inside triple quotes elif in_triple == q: in_triple = None # else: ignore mismatched triple quote while inside return mask
def _strip(self, lines): return [self.prompt_re.sub('', l, count=1) for l in lines]
def __call__(self, lines): if not lines: return lines
if self.doctest: triple_mask = self._triple_quote_mask(lines)
# Detect doctest prompts only outside triple-quoted strings. has_doctest_outside = any( (not in_triple) and self._doctest_initial_re.match(l) for l, in_triple in zip(lines, triple_mask) ) if not has_doctest_outside: return lines
out_lines: List[str] = [] stripped_mask: List[bool] = []
for l, in_triple in zip(lines, triple_mask): if in_triple: out_lines.append(l) stripped_mask.append(False) continue
if self._doctest_ps1_re.match(l): new_l = self._doctest_ps1_re.sub('', l, count=1) elif self._doctest_ps2_re.match(l): new_l = self._doctest_ps2_re.sub('', l, count=1) else: new_l = l out_lines.append(new_l) stripped_mask.append(new_l != l)
# Dedent only the non-triple-quoted segments where stripping occurred. dedented: List[str] = [] i = 0 while i < len(out_lines): j = i in_triple = triple_mask[i] while j < len(out_lines) and triple_mask[j] == in_triple: j += 1
segment = out_lines[i:j] seg_stripped = any(stripped_mask[i:j])
if (not in_triple) and seg_stripped: dedented.extend(dedent(''.join(segment)).splitlines(keepends=True)) else: dedented.extend(segment)
i = j
return dedented
if self.initial_re.match(lines[0]) or \ (len(lines) > 1 and self.prompt_re.match(lines[1])): return self._strip(lines) return lines
classic_prompt = PromptStripper( prompt_re=re.compile(r'^(>>>|\.\.\.)( |$)'), initial_re=re.compile(r'^>>>( |$)'), doctest=True,)
ipython_prompt = PromptStripper( re.compile( r""" ^( # Match from the beginning of a line, either:
# 1. First-line prompt: ((\[nav\]|\[ins\])?\ )? # Vi editing mode prompt, if it's there In\ # The 'In' of the prompt, with a space \[\d+\]: # Command index, as displayed in the prompt \ # With a mandatory trailing space
| # ... or ...
# 2. The three dots of the multiline prompt \s* # All leading whitespace characters \.{3,}: # The three (or more) dots \ ? # With an optional trailing space
) """, re.VERBOSE, ))
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)]
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
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
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
class TokenTransformBase: """Base class for transformations which examine tokens.
Special syntax should not be transformed when it occurs inside strings or comments. This is hard to reliably avoid with regexes. The solution is to tokenise the code as Python, and recognise the special syntax in the tokens.
IPython's special syntax is not valid Python syntax, so tokenising may go wrong after the special syntax starts. These classes therefore find and transform *one* instance of special syntax at a time into regular Python syntax. After each transformation, tokens are regenerated to find the next piece of special syntax.
Subclasses need to implement one class method (find) and one regular method (transform).
The priority attribute can select which transformation to apply if multiple transformers match in the same place. Lower numbers have higher priority. This allows "%magic?" to be turned into a help call rather than a magic call. """ # Lower numbers -> higher priority (for matches in the same location) priority = 10
def sortby(self): return self.start_line, self.start_col, self.priority
def __init__(self, start): self.start_line = start[0] - 1 # Shift from 1-index to 0-index self.start_col = start[1]
@classmethod def find(cls, tokens_by_line): """Find one instance of special syntax in the provided tokens.
Tokens are grouped into logical lines for convenience, so it is easy to e.g. look at the first token of each line. *tokens_by_line* is a list of lists of tokenize.TokenInfo objects.
This should return an instance of its class, pointing to the start position it has found, or None if it found no match. """ raise NotImplementedError
def transform(self, lines: List[str]): """Transform one instance of special syntax found by ``find()``
Takes a list of strings representing physical lines, returns a similar list of transformed lines. """ raise NotImplementedError
class MagicAssign(TokenTransformBase): """Transformer for assignments from magics (a = %foo)""" @classmethod def find(cls, tokens_by_line): """Find the first magic assignment (a = %foo) in the cell. """ for line in tokens_by_line: assign_ix = _find_assign_op(line) 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): return cls(line[assign_ix+1].start)
def transform(self, lines: List[str]): """Transform a magic assignment found by the ``find()`` classmethod. """ start_line, start_col = self.start_line, self.start_col lhs = lines[start_line][:start_col] end_line = find_end_of_continued_line(lines, start_line) rhs = assemble_continued_line(lines, (start_line, start_col), end_line) assert rhs.startswith('%'), rhs magic_name, _, args = rhs[1:].partition(' ')
lines_before = lines[:start_line] call = "get_ipython().run_line_magic({!r}, {!r})".format(magic_name, args) new_line = lhs + call + '\n' lines_after = lines[end_line+1:]
return lines_before + [new_line] + lines_after
class SystemAssign(TokenTransformBase): """Transformer for assignments from system commands (a = !foo)""" @classmethod def find_pre_312(cls, tokens_by_line): for line in tokens_by_line: assign_ix = _find_assign_op(line) if (assign_ix is not None) \ and not line[assign_ix].line.strip().startswith('=') \ and (len(line) >= assign_ix + 2) \ and (line[assign_ix + 1].type == tokenize.ERRORTOKEN): ix = assign_ix + 1
while ix < len(line) and line[ix].type == tokenize.ERRORTOKEN: if line[ix].string == '!': return cls(line[ix].start) elif not line[ix].string.isspace(): break ix += 1
@classmethod def find_post_312(cls, tokens_by_line): for line in tokens_by_line: assign_ix = _find_assign_op(line) if ( (assign_ix is not None) and not line[assign_ix].line.strip().startswith("=") and (len(line) >= assign_ix + 2) and (line[assign_ix + 1].type == tokenize.OP) and (line[assign_ix + 1].string == "!") ): return cls(line[assign_ix + 1].start)
@classmethod def find(cls, tokens_by_line): """Find the first system assignment (a = !foo) in the cell.""" if sys.version_info < (3, 12): return cls.find_pre_312(tokens_by_line) return cls.find_post_312(tokens_by_line)
def transform(self, lines: List[str]): """Transform a system assignment found by the ``find()`` classmethod. """ start_line, start_col = self.start_line, self.start_col
lhs = lines[start_line][:start_col] end_line = find_end_of_continued_line(lines, start_line) rhs = assemble_continued_line(lines, (start_line, start_col), end_line) assert rhs.startswith('!'), rhs cmd = rhs[1:]
lines_before = lines[:start_line] call = "get_ipython().getoutput({!r})".format(cmd) new_line = lhs + call + '\n' lines_after = lines[end_line + 1:]
return lines_before + [new_line] + lines_after
# The escape sequences that define the syntax transformations IPython will# apply to user input. These can NOT be just changed here: many regular# expressions and other parts of the code may use their hardcoded values, and# for all intents and purposes they constitute the 'IPython syntax', so they# should be considered fixed.
ESC_SHELL = '!' # Send line to underlying system shellESC_SH_CAP = '!!' # Send line to system shell and capture outputESC_HELP = '?' # Find information about objectESC_HELP2 = '??' # Find extra-detailed information about objectESC_MAGIC = '%' # Call magic functionESC_MAGIC2 = '%%' # Call cell-magic functionESC_QUOTE = ',' # Split args on whitespace, quote each as string and callESC_QUOTE2 = ';' # Quote all args as a single string, callESC_PAREN = '/' # Call first argument with rest of line as arguments
ESCAPE_SINGLES = {'!', '?', '%', ',', ';', '/'}ESCAPE_DOUBLES = {'!!', '??'} # %% (cell magic) is handled separately
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)
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, '?')
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, '??')
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)
def _tr_quote(content): "Translate lines escaped with a comma: ," name, _, args = content.partition(' ') return '%s("%s")' % (name, '", "'.join(args.split()) )
def _tr_quote2(content): "Translate lines escaped with a semicolon: ;" name, _, args = content.partition(' ') return '%s("%s")' % (name, args)
def _tr_paren(content): "Translate lines escaped with a slash: /" name, _, args = content.partition(" ") if name == "": raise SyntaxError(f'"{ESC_SHELL}" must be followed by a callable name')
return '%s(%s)' % (name, ", ".join(args.split()))
tr = { ESC_SHELL : 'get_ipython().system({!r})'.format, ESC_SH_CAP : 'get_ipython().getoutput({!r})'.format, ESC_HELP : _tr_help, ESC_HELP2 : _tr_help2, ESC_MAGIC : _tr_magic, ESC_QUOTE : _tr_quote, ESC_QUOTE2 : _tr_quote2, ESC_PAREN : _tr_paren }
class EscapedCommand(TokenTransformBase): """Transformer for escaped commands like %foo, !foo, or /foo""" @classmethod def find(cls, tokens_by_line): """Find the first escaped command (%foo, !foo, etc.) in the cell. """ for line in tokens_by_line: if not line: continue ix = 0 ll = len(line) while ll > ix and line[ix].type in {tokenize.INDENT, tokenize.DEDENT}: ix += 1 if ix >= ll: continue if line[ix].string in ESCAPE_SINGLES: return cls(line[ix].start)
def transform(self, lines): """Transform an escaped line found by the ``find()`` classmethod. """ start_line, start_col = self.start_line, self.start_col
indent = lines[start_line][:start_col] end_line = find_end_of_continued_line(lines, start_line) line = assemble_continued_line(lines, (start_line, start_col), end_line)
if len(line) > 1 and line[:2] in ESCAPE_DOUBLES: escape, content = line[:2], line[2:] else: escape, content = line[:1], line[1:]
if escape in tr: call = tr[escape](content) else: call = ''
lines_before = lines[:start_line] new_line = indent + call + '\n' lines_after = lines[end_line + 1:]
return lines_before + [new_line] + lines_after
_help_end_re = re.compile( r"""(%{0,2} (?!\d)[\w*]+ # Variable name (\.(?!\d)[\w*]+|\[-?[0-9]+\])* # .etc.etc or [0], we only support literal integers. ) (\?\??)$ # ? or ?? """, re.VERBOSE,)
class HelpEnd(TokenTransformBase): """Transformer for help syntax: obj? and obj??""" # This needs to be higher priority (lower number) than EscapedCommand so # that inspecting magics (%foo?) works. priority = 5
def __init__(self, start, q_locn): super().__init__(start) self.q_line = q_locn[0] - 1 # Shift from 1-indexed to 0-indexed self.q_col = q_locn[1]
@classmethod def find(cls, tokens_by_line): """Find the first help command (foo?) in the cell. """ for line in tokens_by_line: # Last token is NEWLINE; look at last but one if len(line) > 2 and line[-2].string == '?': # Find the first token that's not INDENT/DEDENT ix = 0 while line[ix].type in {tokenize.INDENT, tokenize.DEDENT}: ix += 1 return cls(line[ix].start, line[-2].start)
def transform(self, lines): """Transform a help command found by the ``find()`` classmethod. """
piece = "".join(lines[self.start_line : self.q_line + 1]) indent, content = piece[: self.start_col], piece[self.start_col :] lines_before = lines[: self.start_line] lines_after = lines[self.q_line + 1 :]
m = _help_end_re.search(content) if not m: raise SyntaxError(content) assert m is not None, content target = m.group(1) esc = m.group(3)
call = _make_help_call(target, esc) new_line = indent + call + '\n'
return lines_before + [new_line] + lines_after
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 tokenutil.generate_tokens_catch_errors( iter(lines).__next__, extra_errors_to_catch=["expected EOF"] ): 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
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
# Arbitrary limit to prevent getting stuck in infinite loopsTRANSFORM_LOOP_LIMIT = 500
class TransformerManager: """Applies various transformations to a cell or code block.
The key methods for external use are ``transform_cell()`` and ``check_complete()``. """ def __init__(self): self.cleanup_transforms = [ leading_empty_lines, leading_indent, classic_prompt, ipython_prompt, ] self.line_transforms = [ cell_magic, ] self.token_transformers = [ MagicAssign, SystemAssign, EscapedCommand, HelpEnd, ]
def do_one_token_transform(self, lines): """Find and run the transform earliest in the code.
Returns (changed, lines).
This method is called repeatedly until changed is False, indicating that all available transformations are complete.
The tokens following IPython special syntax might not be valid, so the transformed code is retokenised every time to identify the next piece of special syntax. Hopefully long code cells are mostly valid Python, not using lots of IPython special syntax, so this shouldn't be a performance issue. """ tokens_by_line = make_tokens_by_line(lines) candidates = [] for transformer_cls in self.token_transformers: transformer = transformer_cls.find(tokens_by_line) if transformer: candidates.append(transformer)
if not candidates: # Nothing to transform return False, lines ordered_transformers = sorted(candidates, key=TokenTransformBase.sortby) for transformer in ordered_transformers: try: return True, transformer.transform(lines) except SyntaxError: pass return False, lines
def do_token_transforms(self, lines): for _ in range(TRANSFORM_LOOP_LIMIT): changed, lines = self.do_one_token_transform(lines) if not changed: return lines
raise RuntimeError("Input transformation still changing after " "%d iterations. Aborting." % TRANSFORM_LOOP_LIMIT)
def transform_cell(self, cell: str) -> str: """Transforms a cell of input code""" if not cell.endswith('\n'): cell += '\n' # Ensure the cell has a trailing newline lines = cell.splitlines(keepends=True) for transform in self.cleanup_transforms + self.line_transforms: lines = transform(lines)
lines = self.do_token_transforms(lines) return ''.join(lines)
def check_complete(self, cell: str): """Return whether a block of code is ready to execute, or should be continued
Parameters ---------- cell : 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_spaces : int or None The number of spaces by which to indent the next line of code. If status is not 'incomplete', this is None. """ # Remember if the lines ends in a new line. ends_with_newline = False for character in reversed(cell): if character == '\n': ends_with_newline = True break elif character.strip(): break else: continue
if not ends_with_newline: # Append an newline for consistent tokenization # See https://bugs.python.org/issue33899 cell += '\n'
lines = cell.splitlines(keepends=True)
if not lines: return 'complete', None
for line in reversed(lines): if not line.strip(): continue elif line.strip("\n").endswith("\\"): return "incomplete", find_last_indent(lines) else: break
try: for transform in self.cleanup_transforms: if not getattr(transform, 'has_side_effects', False): lines = transform(lines) except SyntaxError: return 'invalid', None
if lines[0].startswith('%%'): # Special case for cell magics - completion marked by blank line if lines[-1].strip(): return 'incomplete', find_last_indent(lines) else: return 'complete', None
try: for transform in self.line_transforms: if not getattr(transform, 'has_side_effects', False): lines = transform(lines) lines = self.do_token_transforms(lines) except SyntaxError: return 'invalid', None
tokens_by_line = make_tokens_by_line(lines)
# Bail if we got one line and there are more closing parentheses than # the opening ones if ( len(lines) == 1 and tokens_by_line and has_sunken_brackets(tokens_by_line[0]) ): return "invalid", None
if not tokens_by_line: return 'incomplete', find_last_indent(lines)
if ( tokens_by_line[-1][-1].type != tokenize.ENDMARKER and tokens_by_line[-1][-1].type != tokenize.ERRORTOKEN ): # We're in a multiline string or expression return 'incomplete', find_last_indent(lines)
newline_types = {tokenize.NEWLINE, tokenize.COMMENT, tokenize.ENDMARKER} # type: ignore
# Pop the last line which only contains DEDENTs and ENDMARKER last_token_line = None if {t.type for t in tokens_by_line[-1]} in [ {tokenize.DEDENT, tokenize.ENDMARKER}, {tokenize.ENDMARKER} ] and len(tokens_by_line) > 1: last_token_line = tokens_by_line.pop()
while tokens_by_line[-1] and tokens_by_line[-1][-1].type in newline_types: tokens_by_line[-1].pop()
if not tokens_by_line[-1]: return 'incomplete', find_last_indent(lines)
if tokens_by_line[-1][-1].string == ':': # The last line starts a block (e.g. 'if foo:') ix = 0 while tokens_by_line[-1][ix].type in {tokenize.INDENT, tokenize.DEDENT}: ix += 1
indent = tokens_by_line[-1][ix].start[1] return 'incomplete', indent + 4
if tokens_by_line[-1][0].line.endswith('\\'): return 'incomplete', None
# At this point, our checks think the code is complete (or invalid). # We'll use codeop.compile_command to check this with the real parser try: with warnings.catch_warnings(): warnings.simplefilter('error', SyntaxWarning) res = compile_command(''.join(lines), symbol='exec') except (SyntaxError, OverflowError, ValueError, TypeError, MemoryError, SyntaxWarning): return 'invalid', None else: if res is None: return 'incomplete', find_last_indent(lines)
if last_token_line and last_token_line[0].type == tokenize.DEDENT: if ends_with_newline: return 'complete', None return 'incomplete', find_last_indent(lines)
# If there's a blank line at the end, assume we're ready to execute if not lines[-1].strip(): return 'complete', None
return 'complete', None
def find_last_indent(lines): m = _indent_re.match(lines[-1]) if not m: return 0 return len(m.group(0).replace('\t', ' '*4))
class MaybeAsyncCompile(Compile): def __init__(self, extra_flags=0): super().__init__() self.flags |= extra_flags
class MaybeAsyncCommandCompiler(CommandCompiler): def __init__(self, extra_flags=0): self.compiler = MaybeAsyncCompile(extra_flags=extra_flags)
_extra_flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
compile_command = MaybeAsyncCommandCompiler(extra_flags=_extra_flags)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Support for interactive macros in IPython"""
#*****************************************************************************# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#*****************************************************************************
import re
from IPython.utils.encoding import DEFAULT_ENCODING
coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
class Macro: """Simple class to store the value of macros as strings.
Macro is just a callable that executes a string of IPython input when called. """
def __init__(self,code): """store the macro value, as a single string which can be executed""" lines = [] enc = None for line in code.splitlines(): coding_match = coding_declaration.match(line) if coding_match: enc = coding_match.group(1) else: lines.append(line) code = "\n".join(lines) if isinstance(code, bytes): code = code.decode(enc or DEFAULT_ENCODING) self.value = code + '\n' def __str__(self): return self.value
def __repr__(self): return 'IPython.macro.Macro(%s)' % repr(self.value) def __getstate__(self): """ needed for safe pickling via %store """ return {'value': self.value} def __add__(self, other): if isinstance(other, Macro): return Macro(self.value + other.value) elif isinstance(other, str): return Macro(self.value + other) raise TypeError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312'''A decorator-based method of constructing IPython magics with `argparse`option handling.
New magic functions can be defined like so::
from IPython.core.magic_arguments import (argument, magic_arguments, parse_argstring)
@magic_arguments() @argument('-o', '--option', help='An optional argument.') @argument('arg', type=int, help='An integer positional argument.') def magic_cool(self, arg): """ A really cool magic command.
""" args = parse_argstring(magic_cool, arg) ...
The `@magic_arguments` decorator marks the function as having argparse arguments.The `@argument` decorator adds an argument using the same syntax as argparse's`add_argument()` method. More sophisticated uses may also require the`@argument_group` or `@kwds` decorator to customize the formatting and theparsing.
Help text for the magic is automatically generated from the docstring and thearguments::
In[1]: %cool? %cool [-o OPTION] arg
A really cool magic command.
positional arguments: arg An integer positional argument.
optional arguments: -o OPTION, --option OPTION An optional argument.
Here is an elaborated example that uses default parameters in `argument` and calls the `args` in the cell magic::
from IPython.core.magic import register_cell_magic from IPython.core.magic_arguments import (argument, magic_arguments, parse_argstring)
@magic_arguments() @argument( "--option", "-o", help=("Add an option here"), ) @argument( "--style", "-s", default="foo", help=("Add some style arguments"), ) @register_cell_magic def my_cell_magic(line, cell): args = parse_argstring(my_cell_magic, line) print(f"{args.option=}") print(f"{args.style=}") print(f"{cell=}")
In a jupyter notebook, this cell magic can be executed like this::
%%my_cell_magic -o Hello print("bar") i = 42
Inheritance diagram:
.. inheritance-diagram:: IPython.core.magic_arguments :parts: 3
'''#-----------------------------------------------------------------------------# Copyright (C) 2010-2011, IPython Development Team.## Distributed under the terms of the Modified BSD License.## The full license is in the file COPYING.txt, distributed with this software.#-----------------------------------------------------------------------------import argparseimport re
# Our own importsfrom IPython.core.error import UsageErrorfrom IPython.utils.decorators import undocfrom IPython.utils.process import arg_splitfrom IPython.utils.text import dedent
NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$")
@undocclass MagicHelpFormatter(argparse.RawDescriptionHelpFormatter): """A HelpFormatter with a couple of changes to meet our needs. """ # Modified to dedent text. def _fill_text(self, text, width, indent): return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
# Modified to wrap argument placeholders in <> where necessary. def _format_action_invocation(self, action): if not action.option_strings: metavar, = self._metavar_formatter(action, action.dest)(1) return metavar
else: parts = []
# if the Optional doesn't take a value, format is: # -s, --long if action.nargs == 0: parts.extend(action.option_strings)
# if the Optional takes a value, format is: # -s ARGS, --long ARGS else: default = action.dest.upper() args_string = self._format_args(action, default) # IPYTHON MODIFICATION: If args_string is not a plain name, wrap # it in <> so it's valid RST. if not NAME_RE.match(args_string): args_string = "<%s>" % args_string for option_string in action.option_strings: parts.append('%s %s' % (option_string, args_string))
return ', '.join(parts)
# Override the default prefix ('usage') to our % magic escape, # in a code block. def add_usage(self, usage, actions, groups, prefix="::\n\n %"): super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)
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, *, partial=False): """ Split a string into an argument list and parse that argument list. """ argv = arg_split(argstring, strict=not partial) if partial: return self.parse_known_args(argv) return self.parse_args(argv)
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
def parse_argstring(magic_func, argstring, *, partial=False): """ Parse the string of arguments for the given magic function. """ return magic_func.parser.parse_argstring(argstring, partial=partial)
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 ArgDecorator: """ Base class for decorators to add ArgumentParser information to a method. """
def __call__(self, func): if not getattr(func, 'has_arguments', False): func.has_arguments = True func.decorators = [] func.decorators.append(self) return func
def add_to_parser(self, parser, group): """ Add this object's information to the parser, if necessary. """ pass
class magic_arguments(ArgDecorator): """ Mark the magic as having argparse arguments and possibly adjust the name. """
def __init__(self, name=None): self.name = name
def __call__(self, func): if not getattr(func, 'has_arguments', False): func.has_arguments = True func.decorators = [] if self.name is not None: func.argcmd_name = self.name # This should be the first decorator in the list of decorators, thus the # last to execute. Build the parser. func.parser = construct_parser(func) return func
class ArgMethodWrapper(ArgDecorator):
""" Base class to define a wrapper for ArgumentParser method.
Child class must define either `_method_name` or `add_to_parser`.
"""
_method_name: str
def __init__(self, *args, **kwds): self.args = args self.kwds = kwds
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ if group is not None: parser = group getattr(parser, self._method_name)(*self.args, **self.kwds) return None
class argument(ArgMethodWrapper): """ Store arguments and keywords to pass to add_argument().
Instances also serve to decorate command methods. """ _method_name = 'add_argument'
class defaults(ArgMethodWrapper): """ Store arguments and keywords to pass to set_defaults().
Instances also serve to decorate command methods. """ _method_name = 'set_defaults'
class argument_group(ArgMethodWrapper): """ Store arguments and keywords to pass to add_argument_group().
Instances also serve to decorate command methods. """
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ return parser.add_argument_group(*self.args, **self.kwds)
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
__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds', 'parse_argstring']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215"""Tools for inspecting Python objects.
Uses syntax highlighting for presenting the various information elements.
Similar in spirit to the inspect module, but all calls take a name argument toreference the name under which an object is being read."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
__all__ = ["Inspector"]
# stdlib modulesfrom dataclasses import dataclassfrom inspect import signaturefrom textwrap import dedentimport astimport htmlimport inspectimport io as stdlib_ioimport linecacheimport osimport typesimport warningsfrom pygments.token import Token
from typing import ( cast, Any, Optional, Dict, Union, List, TypedDict, TypeAlias, Tuple,)
import traitletsfrom traitlets.config import Configurable
# IPython's ownfrom IPython.core import pagefrom IPython.lib.pretty import prettyfrom IPython.testing.skipdoctest import skip_doctestfrom IPython.utils import PyColorize, openpyfrom IPython.utils.dir2 import safe_hasattrfrom IPython.utils.path import compress_userfrom IPython.utils.text import indentfrom IPython.utils.wildcard import list_namespace, typestr2typefrom IPython.utils.decorators import undoc
from pygments import highlightfrom pygments.lexers import PythonLexerfrom pygments.formatters import HtmlFormatter
HOOK_NAME = "__custom_documentations__"
UnformattedBundle: TypeAlias = Dict[str, List[Tuple[str, str]]] # List of (title, body)Bundle: TypeAlias = Dict[str, str]
@dataclassclass OInfo: ismagic: bool isalias: bool found: bool namespace: Optional[str] parent: Any obj: Any
def get(self, field): """Get a field from the object for backward compatibility with before 8.12
see https://github.com/h5py/h5py/issues/2253 """ # We need to deprecate this at some point, but the warning will show in completion. # Let's comment this for now and uncomment end of 2023 ish # Jan 2025: decomenting for IPython 9.0 warnings.warn( f"OInfo dataclass with fields access since IPython 8.12 please use OInfo.{field} instead." "OInfo used to be a dict but a dataclass provide static fields verification with mypy." "This warning and backward compatibility `get()` method were added in 8.13.", DeprecationWarning, stacklevel=2, ) return getattr(self, field)
def pylight(code): return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
# builtin docstrings to ignore_func_call_docstring = types.FunctionType.__call__.__doc___object_init_docstring = object.__init__.__doc___builtin_type_docstrings = { inspect.getdoc(t) for t in (types.ModuleType, types.MethodType, types.FunctionType, property)}
_builtin_func_type = type(all)_builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions#****************************************************************************# Builtin color schemes
#****************************************************************************# Auxiliary functions and objects
class InfoDict(TypedDict): type_name: Optional[str] base_class: Optional[str] string_form: Optional[str] namespace: Optional[str] length: Optional[str] file: Optional[str] definition: Optional[str] docstring: Optional[str] source: Optional[str] init_definition: Optional[str] class_docstring: Optional[str] init_docstring: Optional[str] call_def: Optional[str] call_docstring: Optional[str] subclasses: Optional[str] # These won't be printed but will be used to determine how to # format the object ismagic: bool isalias: bool isclass: bool found: bool name: str
_info_fields = list(InfoDict.__annotations__.keys())
def __getattr__(name): if name == "info_fields": warnings.warn( "IPython.core.oinspect's `info_fields` is considered for deprecation and may be removed in the Future. ", DeprecationWarning, stacklevel=2, ) return _info_fields
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@dataclassclass InspectorHookData: """Data passed to the mime hook"""
obj: Any info: Optional[OInfo] info_dict: InfoDict detail_level: int omit_sections: list[str]
@undocdef object_info( *, name: str, found: bool, isclass: bool = False, isalias: bool = False, ismagic: bool = False, **kw,) -> InfoDict: """Make an object info dict with all fields present.""" infodict = dict(kw) infodict.update({k: None for k in _info_fields if k not in infodict}) infodict["name"] = name # type: ignore infodict["found"] = found # type: ignore infodict["isclass"] = isclass # type: ignore infodict["isalias"] = isalias # type: ignore infodict["ismagic"] = ismagic # type: ignore
return InfoDict(**infodict) # type:ignore
def get_encoding(obj): """Get encoding for python source file defining obj
Returns None if obj is not defined in a sourcefile. """ ofile = find_file(obj) # run contents of file through pager starting at line where the object # is defined, as long as the file isn't binary and is actually on the # filesystem. if ofile is None: return None elif ofile.endswith(('.so', '.dll', '.pyd')): return None elif not os.path.isfile(ofile): return None else: # Print only text files, not extension binaries. Note that # getsourcelines returns lineno with 1-offset and page() uses # 0-offset, so we must adjust. with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2 encoding, _lines = openpy.detect_encoding(buffer.readline) return encoding
def getdoc(obj) -> Union[str, None]: """Stable wrapper around inspect.getdoc.
This can't crash because of attribute problems.
It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipython's ? system. """ # Allow objects to offer customized documentation via a getdoc method: try: ds = obj.getdoc() except Exception: pass else: if isinstance(ds, str): return inspect.cleandoc(ds) docstr = inspect.getdoc(obj) return docstr
def getsource(obj, oname='') -> Union[str,None]: """Wrapper around inspect.getsource.
This can be modified by other projects to provide customized source extraction.
Parameters ---------- obj : object an object whose source code we will attempt to extract oname : str (optional) a name under which the object is known
Returns ------- src : unicode or None
"""
if isinstance(obj, property): sources = [] for attrname in ['fget', 'fset', 'fdel']: fn = getattr(obj, attrname) if fn is not None: oname_prefix = ('%s.' % oname) if oname else '' sources.append(''.join(('# ', oname_prefix, attrname))) if inspect.isfunction(fn): _src = getsource(fn) if _src: # assert _src is not None, "please mypy" sources.append(dedent(_src)) else: # Default str/repr only prints function name, # pretty.pretty prints module name too. sources.append( '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn)) ) if sources: return '\n'.join(sources) else: return None
else: # Get source for non-property objects.
obj = _get_wrapped(obj)
try: src = inspect.getsource(obj) except TypeError: # The object itself provided no meaningful source, try looking for # its class definition instead. try: src = inspect.getsource(obj.__class__) except (OSError, TypeError): return None except OSError: return None
return src
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 _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
def find_file(obj) -> Optional[str]: """Find the absolute path to the file where an object was defined.
This is essentially a robust wrapper around `inspect.getabsfile`.
Returns None if no file can be found.
Parameters ---------- obj : any Python object
Returns ------- fname : str The absolute path to the file where the object was defined. """ obj = _get_wrapped(obj)
fname: Optional[str] = None try: fname = inspect.getabsfile(obj) except TypeError: # For an instance, the file that matters is where its class was # declared. try: fname = inspect.getabsfile(obj.__class__) except (OSError, TypeError): # Can happen for builtins pass except OSError: pass
return fname
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
_sentinel = object()
class Inspector(Configurable): mime_hooks = traitlets.Dict( config=True, help="dictionary of mime to callable to add information into help mimebundle dict", ).tag(config=True)
_theme_name: str
def __init__( self, *, theme_name: str, str_detail_level=0, parent=None, config=None, ): if theme_name in ["Linux", "LightBG", "Neutral", "NoColor"]: warnings.warn( f"Theme names and color schemes are lowercase in IPython 9.0 use {theme_name.lower()} instead", DeprecationWarning, stacklevel=2, ) theme_name = theme_name.lower() self._theme_name = theme_name super(Inspector, self).__init__(parent=parent, config=config) self.parser = PyColorize.Parser(out="str", theme_name=theme_name) self.str_detail_level = str_detail_level self.set_theme_name(theme_name)
def format(self, *args, **kwargs): return self.parser.format(*args, **kwargs)
def _getdef(self,obj,oname='') -> Union[str,None]: """Return the call signature for any callable object.
If any exception is generated, None is returned instead and the exception is suppressed.""" if not callable(obj): return None try: return _render_signature(signature(obj), oname) except: return None
def __head(self, h: str) -> str: """Return a header string with proper colors.""" return PyColorize.theme_table[self._theme_name].format([(Token.Header, h)])
def set_theme_name(self, name: str): assert name == name.lower() assert name in PyColorize.theme_table.keys() self._theme_name = name self.parser.theme_name = name
def set_active_scheme(self, scheme: str): warnings.warn( "set_active_scheme is deprecated and replaced by set_theme_name as of IPython 9.0", DeprecationWarning, stacklevel=2, ) assert scheme == scheme.lower() if scheme is not None and self._theme_name != scheme: self._theme_name = scheme self.parser.theme_name = scheme
def noinfo(self, msg, oname): """Generic message when no information is found.""" print('No %s found' % msg, end=' ') if oname: print('for %s' % oname) else: print()
def pdef(self, obj, oname=''): """Print the call signature for any callable object.
If the object is a class, print the constructor information."""
if not callable(obj): print('Object is not callable.') return
header = ''
if inspect.isclass(obj): header = self.__head('Class constructor information:\n')
output = self._getdef(obj,oname) if output is None: self.noinfo('definition header',oname) else: print(header,self.format(output), end=' ')
# In Python 3, all classes are new-style, so they all have __init__. @skip_doctest def pdoc(self, obj, oname='', formatter=None): """Print the docstring for any object.
Optional: -formatter: a function to run the docstring through for specially formatted docstrings.
Examples -------- In [1]: class NoInit: ...: pass
In [2]: class NoDoc: ...: def __init__(self): ...: pass
In [3]: %pdoc NoDoc No documentation found for NoDoc
In [4]: %pdoc NoInit No documentation found for NoInit
In [5]: obj = NoInit()
In [6]: %pdoc obj No documentation found for obj
In [5]: obj2 = NoDoc()
In [6]: %pdoc obj2 No documentation found for obj2 """
lines = [] ds = getdoc(obj) if formatter: ds = formatter(ds).get('plain/text', ds) if ds: lines.append(self.__head("Class docstring:")) lines.append(indent(ds)) if inspect.isclass(obj) and hasattr(obj, '__init__'): init_ds = getdoc(obj.__init__) if init_ds is not None: lines.append(self.__head("Init docstring:")) lines.append(indent(init_ds)) elif hasattr(obj,'__call__'): call_ds = getdoc(obj.__call__) if call_ds: lines.append(self.__head("Call docstring:")) lines.append(indent(call_ds))
if not lines: self.noinfo('documentation',oname) else: page.page('\n'.join(lines))
def psource(self, obj, oname=''): """Print the source code for an object."""
# Flush the source cache because inspect can return out-of-date source linecache.checkcache() try: src = getsource(obj, oname=oname) except Exception: src = None
if src is None: self.noinfo('source', oname) else: page.page(self.format(src))
def pfile(self, obj, oname=''): """Show the whole file where an object was defined."""
lineno = find_source_lines(obj) if lineno is None: self.noinfo('file', oname) return
ofile = find_file(obj) # run contents of file through pager starting at line where the object # is defined, as long as the file isn't binary and is actually on the # filesystem. if ofile is None: print("Could not find file for object") elif ofile.endswith((".so", ".dll", ".pyd")): print("File %r is binary, not printing." % ofile) elif not os.path.isfile(ofile): print('File %r does not exist, not printing.' % ofile) else: # Print only text files, not extension binaries. Note that # getsourcelines returns lineno with 1-offset and page() uses # 0-offset, so we must adjust. page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
def _mime_format(self, text:str, formatter=None) -> dict: """Return a mime bundle representation of the input text.
- if `formatter` is None, the returned mime bundle has a ``text/plain`` field, with the input text. a ``text/html`` field with a ``<pre>`` tag containing the input text.
- if ``formatter`` is not None, it must be a callable transforming the input text into a mime bundle. Default values for ``text/plain`` and ``text/html`` representations are the ones described above.
Note:
Formatters returning strings are supported but this behavior is deprecated.
""" defaults = { "text/plain": text, "text/html": f"<pre>{html.escape(text)}</pre>", }
if formatter is None: return defaults else: formatted = formatter(text)
if not isinstance(formatted, dict): # Handle the deprecated behavior of a formatter returning # a string instead of a mime bundle. return {"text/plain": formatted, "text/html": f"<pre>{formatted}</pre>"}
else: return dict(defaults, **formatted)
def format_mime(self, bundle: UnformattedBundle) -> Bundle: """Format a mimebundle being created by _make_info_unformatted into a real mimebundle""" # Format text/plain mimetype assert isinstance(bundle["text/plain"], list) for item in bundle["text/plain"]: assert isinstance(item, tuple)
new_b: Bundle = {} lines = [] _len = max(len(h) for h, _ in bundle["text/plain"])
for head, body in bundle["text/plain"]: body = body.strip("\n") delim = "\n" if "\n" in body else " " lines.append( f"{self.__head(head+':')}{(_len - len(head))*' '}{delim}{body}" )
new_b["text/plain"] = "\n".join(lines)
if "text/html" in bundle: assert isinstance(bundle["text/html"], list) for item in bundle["text/html"]: assert isinstance(item, tuple) # Format the text/html mimetype if isinstance(bundle["text/html"], (list, tuple)): # bundle['text/html'] is a list of (head, formatted body) pairs new_b["text/html"] = "\n".join( f"<h1>{head}</h1>\n{body}" for (head, body) in bundle["text/html"] )
for k in bundle.keys(): if k in ("text/html", "text/plain"): continue else: new_b[k] = bundle[k] # type:ignore return new_b
def _append_info_field( self, bundle: UnformattedBundle, title: str, key: str, info, omit_sections: List[str], formatter, ): """Append an info value to the unformatted mimebundle being constructed by _make_info_unformatted""" if title in omit_sections or key in omit_sections: return field = info[key] if field is not None: formatted_field = self._mime_format(field, formatter) bundle["text/plain"].append((title, formatted_field["text/plain"])) bundle["text/html"].append((title, formatted_field["text/html"]))
def _make_info_unformatted( self, obj, info, formatter, detail_level, omit_sections ) -> UnformattedBundle: """Assemble the mimebundle as unformatted lists of information""" bundle: UnformattedBundle = { "text/plain": [], "text/html": [], }
# A convenience function to simplify calls below def append_field( bundle: UnformattedBundle, title: str, key: str, formatter=None ): self._append_info_field( bundle, title=title, key=key, info=info, omit_sections=omit_sections, formatter=formatter, )
def code_formatter(text) -> Bundle: return { 'text/plain': self.format(text), 'text/html': pylight(text) }
if info["isalias"]: append_field(bundle, "Repr", "string_form")
elif info['ismagic']: if detail_level > 0: append_field(bundle, "Source", "source", code_formatter) else: append_field(bundle, "Docstring", "docstring", formatter) append_field(bundle, "File", "file")
elif info['isclass'] or is_simple_callable(obj): # Functions, methods, classes append_field(bundle, "Signature", "definition", code_formatter) append_field(bundle, "Init signature", "init_definition", code_formatter) append_field(bundle, "Docstring", "docstring", formatter) if detail_level > 0 and info["source"]: append_field(bundle, "Source", "source", code_formatter) else: append_field(bundle, "Init docstring", "init_docstring", formatter)
append_field(bundle, "File", "file") append_field(bundle, "Type", "type_name") append_field(bundle, "Subclasses", "subclasses")
else: # General Python objects append_field(bundle, "Signature", "definition", code_formatter) append_field(bundle, "Call signature", "call_def", code_formatter) append_field(bundle, "Type", "type_name") append_field(bundle, "String form", "string_form")
# Namespace if info["namespace"] != "Interactive": append_field(bundle, "Namespace", "namespace")
append_field(bundle, "Length", "length") append_field(bundle, "File", "file")
# Source or docstring, depending on detail level and whether # source found. if detail_level > 0 and info["source"]: append_field(bundle, "Source", "source", code_formatter) else: append_field(bundle, "Docstring", "docstring", formatter)
append_field(bundle, "Class docstring", "class_docstring", formatter) append_field(bundle, "Init docstring", "init_docstring", formatter) append_field(bundle, "Call docstring", "call_docstring", formatter) return bundle
def _get_info( self, obj: Any, oname: str = "", formatter=None, info: Optional[OInfo] = None, detail_level: int = 0, omit_sections: Union[List[str], Tuple[()]] = (), ) -> Bundle: """Retrieve an info dict and format it.
Parameters ---------- obj : any Object to inspect and return info from oname : str (default: ''): Name of the variable pointing to `obj`. formatter : callable info already computed information detail_level : integer Granularity of detail level, if set to 1, give more information. omit_sections : list[str] Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`) """
info_dict = self.info(obj, oname=oname, info=info, detail_level=detail_level) omit_sections = list(omit_sections)
bundle = self._make_info_unformatted( obj, info_dict, formatter, detail_level=detail_level, omit_sections=omit_sections, ) if self.mime_hooks: hook_data = InspectorHookData( obj=obj, info=info, info_dict=info_dict, detail_level=detail_level, omit_sections=omit_sections, ) for key, hook in self.mime_hooks.items(): # type:ignore required_parameters = [ parameter for parameter in inspect.signature(hook).parameters.values() if parameter.default != inspect.Parameter.default ] if len(required_parameters) == 1: res = hook(hook_data) else: warnings.warn( "MIME hook format changed in IPython 8.22; hooks should now accept" " a single parameter (InspectorHookData); support for hooks requiring" " two-parameters (obj and info) will be removed in a future version", DeprecationWarning, stacklevel=2, ) res = hook(obj, info) if res is not None: bundle[key] = res return self.format_mime(bundle)
def pinfo( self, obj, oname="", formatter=None, info: Optional[OInfo] = None, detail_level=0, enable_html_pager=True, omit_sections=(), ): """Show detailed information about an object.
Optional arguments:
- oname: name of the variable pointing to the object.
- formatter: callable (optional) A special formatter for docstrings.
The formatter is a callable that takes a string as an input and returns either a formatted string or a mime type bundle in the form of a dictionary.
Although the support of custom formatter returning a string instead of a mime type bundle is deprecated.
- info: a structure with some information fields which may have been precomputed already.
- detail_level: if set to 1, more information is given.
- omit_sections: set of section keys and titles to omit """ assert info is not None info_b: Bundle = self._get_info( obj, oname, formatter, info, detail_level, omit_sections=omit_sections ) if not enable_html_pager: del info_b["text/html"] page.page(info_b)
def info(self, obj, oname="", info=None, detail_level=0) -> InfoDict: """Compute a dict with detailed information about an object.
Parameters ---------- obj : any An object to find information about oname : str (default: '') Name of the variable pointing to `obj`. info : (default: None) A struct (dict like with attr access) with some information fields which may have been precomputed already. detail_level : int (default:0) If set to 1, more information is given.
Returns ------- An object info dict with known fields from `info_fields` (see `InfoDict`). """
if info is None: ismagic = False isalias = False ospace = '' else: ismagic = info.ismagic isalias = info.isalias ospace = info.namespace
# Get docstring, special-casing aliases: att_name = oname.split(".")[-1] parents_docs = None prelude = "" if info and info.parent is not None and hasattr(info.parent, HOOK_NAME): parents_docs_dict = getattr(info.parent, HOOK_NAME) parents_docs = parents_docs_dict.get(att_name, None) out: InfoDict = cast( InfoDict, { **{field: None for field in _info_fields}, **{ "name": oname, "found": True, "isalias": isalias, "ismagic": ismagic, "subclasses": None, }, }, )
if parents_docs: ds = parents_docs elif isalias: if not callable(obj): try: ds = "Alias to the system command:\n %s" % obj[1] except: ds = "Alias: " + str(obj) else: ds = "Alias to " + str(obj) if obj.__doc__: ds += "\nDocstring:\n" + obj.__doc__ else: ds_or_None = getdoc(obj) if ds_or_None is None: ds = '<no docstring>' else: ds = ds_or_None
ds = prelude + ds
# store output in a dict, we initialize it here and fill it as we go
string_max = 200 # max size of strings to show (snipped if longer) shalf = int((string_max - 5) / 2)
if ismagic: out['type_name'] = 'Magic function' elif isalias: out['type_name'] = 'System alias' else: out['type_name'] = type(obj).__name__
try: bclass = obj.__class__ out['base_class'] = str(bclass) except: pass
# String form, but snip if too long in ? form (full in ??) if detail_level >= self.str_detail_level: try: ostr = str(obj) if not detail_level and len(ostr) > string_max: ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] # TODO: `'string_form'.expandtabs()` seems wrong, but # it was (nearly) like this since the first commit ever. ostr = ("\n" + " " * len("string_form".expandtabs())).join( q.strip() for q in ostr.split("\n") ) out["string_form"] = ostr except: pass
if ospace: out['namespace'] = ospace
# Length (for strings and lists) try: out['length'] = str(len(obj)) except Exception: pass
# Filename where object was defined binary_file = False fname = find_file(obj) if fname is None: # if anything goes wrong, we don't want to show source, so it's as # if the file was binary binary_file = True else: if fname.endswith(('.so', '.dll', '.pyd')): binary_file = True elif fname.endswith('<string>'): fname = 'Dynamically generated function. No source code available.' out['file'] = compress_user(fname)
# Original source code for a callable, class or property. if detail_level: # Flush the source cache because inspect can return out-of-date # source linecache.checkcache() try: if isinstance(obj, property) or not binary_file: src = getsource(obj, oname) if src is not None: src = src.rstrip() out['source'] = src
except Exception: pass
# Add docstring only if no source is to be shown (avoid repetitions). if ds and not self._source_contains_docstring(out.get('source'), ds): out['docstring'] = ds
# Constructor docstring for classes if inspect.isclass(obj): out['isclass'] = True
# get the init signature: try: init_def = self._getdef(obj, oname) except AttributeError: init_def = None
# get the __init__ docstring try: obj_init = obj.__init__ except AttributeError: init_ds = None else: if init_def is None: # Get signature from init if top-level sig failed. # Can happen for built-in types (list, etc.). try: init_def = self._getdef(obj_init, oname) except AttributeError: pass init_ds = getdoc(obj_init) # Skip Python's auto-generated docstrings if init_ds == _object_init_docstring: init_ds = None
if init_def: out['init_definition'] = init_def
if init_ds: out['init_docstring'] = init_ds
names = [sub.__name__ for sub in type.__subclasses__(obj)] if len(names) < 10: all_names = ', '.join(names) else: all_names = ', '.join(names[:10]+['...']) out['subclasses'] = all_names # and class docstring for instances: else: # reconstruct the function definition and print it: defln = self._getdef(obj, oname) if defln: out['definition'] = defln
# First, check whether the instance docstring is identical to the # class one, and print it separately if they don't coincide. In # most cases they will, but it's nice to print all the info for # objects which use instance-customized docstrings. if ds: try: cls = getattr(obj,'__class__') except: class_ds = None else: class_ds = getdoc(cls) # Skip Python's auto-generated docstrings if class_ds in _builtin_type_docstrings: class_ds = None if class_ds and ds != class_ds: out['class_docstring'] = class_ds
# Next, try to show constructor docstrings try: init_ds = getdoc(obj.__init__) # Skip Python's auto-generated docstrings if init_ds == _object_init_docstring: init_ds = None except AttributeError: init_ds = None if init_ds: out['init_docstring'] = init_ds
# Call form docstring for callable instances if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): call_def = self._getdef(obj.__call__, oname) if call_def and (call_def != out.get('definition')): # it may never be the case that call def and definition differ, # but don't include the same signature twice out['call_def'] = call_def call_ds = getdoc(obj.__call__) # Skip Python's auto-generated docstrings if call_ds == _func_call_docstring: call_ds = None if call_ds: out['call_docstring'] = call_ds
return out
@staticmethod def _source_contains_docstring(src, doc): """ Check whether the source *src* contains the docstring *doc*.
This is is helper function to skip displaying the docstring if the source already contains it, avoiding repetition of information. """ try: (def_node,) = ast.parse(dedent(src)).body return ast.get_docstring(def_node) == doc # type: ignore[arg-type] except Exception: # The source can become invalid or even non-existent (because it # is re-fetched from the source file) so the above code fail in # arbitrary ways. return False
def psearch(self,pattern,ns_table,ns_search=[], ignore_case=False,show_all=False, *, list_types=False): """Search namespaces with wildcards for objects.
Arguments:
- pattern: string containing shell-like wildcards to use in namespace searches and optionally a type specification to narrow the search to objects of that type.
- ns_table: dict of name->namespaces for search.
Optional arguments:
- ns_search: list of namespace names to include in search.
- ignore_case(False): make the search case-insensitive.
- show_all(False): show all names, including those starting with underscores.
- list_types(False): list all available object types for object matching. """ # print('ps pattern:<%r>' % pattern) # dbg
# defaults type_pattern = 'all' filter = ''
# list all object types if list_types: page.page('\n'.join(sorted(typestr2type))) return
cmds = pattern.split() len_cmds = len(cmds) if len_cmds == 1: # Only filter pattern given filter = cmds[0] elif len_cmds == 2: # Both filter and type specified filter,type_pattern = cmds else: raise ValueError('invalid argument string for psearch: <%s>' % pattern)
# filter search namespaces for name in ns_search: if name not in ns_table: raise ValueError('invalid namespace <%s>. Valid names: %s' % (name,ns_table.keys()))
# print('type_pattern:',type_pattern) # dbg search_result, namespaces_seen = set(), set() for ns_name in ns_search: ns = ns_table[ns_name] # Normally, locals and globals are the same, so we just check one. if id(ns) in namespaces_seen: continue namespaces_seen.add(id(ns)) tmp_res = list_namespace(ns, type_pattern, filter, ignore_case=ignore_case, show_all=show_all) search_result.update(tmp_res)
page.page('\n'.join(sorted(search_result)))
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 rendered123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348# encoding: utf-8"""Paging capabilities for IPython.core
Notes-----
For now this uses IPython hooks, so it can't be in IPython.utils. If we can getrid of that dependency, we could move it there.-----"""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import osimport ioimport reimport sysimport tempfileimport subprocess
from io import UnsupportedOperationfrom pathlib import Path
from IPython import get_ipythonfrom IPython.display import displayfrom IPython.core.error import TryNextfrom IPython.utils.data import chopfrom IPython.utils.process import systemfrom IPython.utils.terminal import get_terminal_sizefrom IPython.utils import py3compat
def display_page(strng, start=0, screen_lines=25): """Just display, no paging. screen_lines is ignored.""" if isinstance(strng, dict): data = strng else: if start: strng = u'\n'.join(strng.splitlines()[start:]) data = { 'text/plain': strng } display(data, raw=True)
def as_hook(page_func): """Wrap a pager func to strip the `self` arg
so it can be called as a hook. """ return lambda self, *args, **kwargs: page_func(*args, **kwargs)
esc_re = re.compile(r"(\x1b[^m]+m)")
def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and mode. """ if isinstance(strng, dict): strng = strng.get('text/plain', '') out_ln = strng.splitlines()[start:] screens = chop(out_ln,screen_lines-1) if len(screens) == 1: print(os.linesep.join(screens[0])) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) print(last_escape + hunk) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] print(last_escape + os.linesep.join(screens[-1]))
def _detect_screen_size(screen_lines_def): """Attempt to work out the number of lines on the screen.
This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block. """ TERM = os.environ.get('TERM',None) if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'): # curses causes problems on many terminals other than xterm, and # some termios calls lock up on Sun OS5. return screen_lines_def try: import termios import curses except ImportError: return screen_lines_def # There is a bug in curses, where *sometimes* it fails to properly # initialize, and then after the endwin() call is made, the # terminal is left in an unusable state. Rather than trying to # check every time for this (by requesting and comparing termios # flags each time), we just save the initial terminal state and # unconditionally reset it every time. It's cheaper than making # the checks. try: term_flags = termios.tcgetattr(sys.stdout) except termios.error as err: # can fail on Linux 2.6, pager_page will catch the TypeError raise TypeError('termios error: {0}'.format(err)) from err
try: scr = curses.initscr() except AttributeError: # Curses on Solaris may not be complete, so we can't use it there return screen_lines_def screen_lines_real,screen_cols = scr.getmaxyx() curses.endwin()
# Restore terminal state in case endwin() didn't. termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) # Now we have what we needed: the screen size in rows/columns return screen_lines_real # print('***Screen size:',screen_lines_real,'lines x', # screen_cols,'columns.') # dbg
def pager_page(strng, start=0, screen_lines=0, pager_cmd=None) -> None: """Display a string, piping through a pager after a certain length.
strng can be a mime-bundle dict, supplying multiple representations, keyed by mime-type.
The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information).
If you set screen_lines to a number <=0, page() will try to auto-determine your screen size and will only use up to (screen_size+screen_lines) for printing, paging after that. That is, if you want auto-detection but need to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for auto-detection without any lines reserved simply use screen_lines = 0.
If a string won't fit in the allowed lines, it is sent through the specified pager command. If none given, look for PAGER in the environment, and ultimately default to less.
If no system pager works, the string is sent through a 'dumb pager' written in python, very simplistic. """ # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng['text/plain']
# Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM','dumb') if TERM in ['dumb','emacs'] and os.name != 'nt': print(strng) return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] str_toprint = os.linesep.join(str_lines) num_newlines = len(str_lines) len_str = len(str_toprint)
# Dumb heuristics to guesstimate number of on-screen lines the string # takes. Very basic, but good enough for docstrings in reasonable # terminals. If someone later feels like refining it, it's not hard. numlines = max(num_newlines,int(len_str/80)+1)
screen_lines_def = get_terminal_size()[1]
# auto-determine screen size if screen_lines <= 0: try: screen_lines += _detect_screen_size(screen_lines_def) except (TypeError, UnsupportedOperation): print(str_toprint) return
# print('numlines',numlines,'screenlines',screen_lines) # dbg if numlines <= screen_lines : # print('*** normal print') # dbg print(str_toprint) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return # value of a failed system command. If any intermediate attempt # sets retval to 1, at the end we resort to our own page_dumb() pager. pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd,start) if os.name == 'nt': if pager_cmd.startswith('type'): # The default WinXP 'type' command is failing on complex strings. retval = 1 else: fd, tmpname = tempfile.mkstemp('.txt') tmppath = Path(tmpname) try: os.close(fd) with tmppath.open("wt", encoding="utf-8") as tmpfile: tmpfile.write(strng) cmd = "%s < %s" % (pager_cmd, tmppath) # tmpfile needs to be closed for windows if os.system(cmd): retval = 1 else: retval = None finally: Path.unlink(tmppath) else: try: retval = None # Emulate os.popen, but redirect stderr proc = subprocess.Popen( pager_cmd, shell=True, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, ) pager = os._wrap_close( io.TextIOWrapper(proc.stdin, encoding="utf-8"), proc ) try: pager_encoding = pager.encoding or sys.stdout.encoding pager.write(strng) finally: retval = pager.close() except IOError as msg: # broken pipe when user quits if msg.args == (32, 'Broken pipe'): retval = None else: retval = 1 except OSError: # Other strange problems, sometimes seen in Win2k/cygwin retval = 1 if retval is not None: page_dumb(strng,screen_lines=screen_lines)
def page(data, start: int = 0, screen_lines: int = 0, pager_cmd=None): """Display content in a pager, piping through a pager after a certain length.
data can be a mime-bundle dict, supplying multiple representations, keyed by mime-type, or text.
Pager is dispatched via the `show_in_pager` IPython hook. If no hook is registered, `pager_page` will be used. """ # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start)
# first, try the hook ip = get_ipython() if ip: try: ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines) return except TryNext: pass # fallback on default pager return pager_page(data, start, screen_lines, pager_cmd)
def page_file(fname, start=0, pager_cmd=None): """Page a file, using an optional pager command and starting line. """
pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd,start)
try: if os.environ['TERM'] in ['emacs','dumb']: raise EnvironmentError system(pager_cmd + ' ' + fname) except: try: if start > 0: start -= 1 page(open(fname, encoding="utf-8").read(), start) except: print('Unable to show file',repr(fname))
def get_pager_cmd(pager_cmd=None): """Return a pager command.
Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -R' # -R for color control sequences elif os.name in ['nt','dos']: default_pager_cmd = 'type'
if pager_cmd is None: try: pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower(): pager_cmd += ' -R' return pager_cmd
def get_pager_start(pager, start): """Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept. """
if pager in ['less','more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string
# (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': import msvcrt def page_more(): """ Smart pausing between pages
@return: True if need print more lines, False if quit """ sys.stdout.write('---Return to continue, q to quit--- ') ans = msvcrt.getwch() if ans in ("q", "Q"): result = False else: result = True sys.stdout.write("\b"*37 + " "*37 + "\b"*37) return resultelse: def page_more(): ans = py3compat.input('---Return to continue, q to quit--- ') if ans.lower().startswith('q'): return False else: return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# -*- coding: utf-8 -*-"""Payload system for IPython.
Authors:
* Fernando Perez* Brian Granger"""
#-----------------------------------------------------------------------------# Copyright (C) 2008-2011 The IPython Development Team## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------
from traitlets.config.configurable import Configurablefrom traitlets import List
#-----------------------------------------------------------------------------# Main payload class#-----------------------------------------------------------------------------
class PayloadManager(Configurable): _payload: List = List([])
def write_payload(self, data, single=True): """Include or update the specified `data` payload in the PayloadManager.
If a previous payload with the same source exists and `single` is True, it will be overwritten with the new one. """
if not isinstance(data, dict): raise TypeError('Each payload write must be a dict, got: %r' % data)
if single and 'source' in data: source = data['source'] for i, pl in enumerate(self._payload): if 'source' in pl and pl['source'] == source: self._payload[i] = data return
self._payload.append(data)
def read_payload(self): return self._payload
def clear_payload(self): self._payload = []1234567891011121314151617181920212223242526272829303132333435363738394041"""A payload based version of page."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import warningsfrom IPython.core.getipython import get_ipython
# see https://github.com/ipython/ipykernel/issues/1304# this should be moved to ipykernel and removed in the long run.
def page(strng, start=0, screen_lines=0, pager_cmd=None): """Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead.
Parameters ---------- strng : str or mime-dict Text to page, or a mime-type keyed dict of already formatted data. start : int Starting line at which to place the display. """
# Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) shell = get_ipython()
if isinstance(strng, dict): data = strng else: data = {"text/plain": strng} payload = dict( source="page", data=data, start=start, ) shell.payload_manager.write_payload(payload)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707# encoding: utf-8"""Prefiltering components.
Prefilters transform user input before it is exec'd by Python. Thesetransforms are used to implement additional syntax such as !ls and %magic."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
from keyword import iskeywordimport re
from .autocall import IPyAutocallfrom traitlets.config.configurable import Configurablefrom .inputtransformer2 import ( ESC_MAGIC, ESC_QUOTE, ESC_QUOTE2, ESC_PAREN,)from .macro import Macrofrom .splitinput import LineInfo
from traitlets import ( List, Integer, Unicode, Bool, Instance, CRegExp)
#-----------------------------------------------------------------------------# Global utilities, errors and constants#-----------------------------------------------------------------------------
class PrefilterError(Exception): pass
# RegExp to identify potential function namesre_fun_name = re.compile(r'[^\W\d]([\w.]*) *$')
# RegExp to exclude strings with this start from autocalling. In# particular, all binary operators should be excluded, so that if foo is# callable, foo OP bar doesn't become foo(OP bar), which is invalid. The# characters '!=()' don't need to be checked for, as the checkPythonChars# routine explicitly does so, to catch direct calls and rebindings of# existing names.
# Warning: the '-' HAS TO BE AT THE END of the first group, otherwise# it affects the rest of the group in square brackets.re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' r'|^is |^not |^in |^and |^or ')
# try to catch also methods for stuff in lists/tuples/dicts: off# (experimental). For this to work, the line_split regexp would need# to be modified so it wouldn't break things at '['. That line is# nasty enough that I shouldn't change it until I can test it _well_.#self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
# Handler Check Utilitiesdef is_shadowed(identifier, ip): """Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different than ifun, because it can not contain a '.' character.""" # This is much safer than calling ofind, which can change state return (identifier in ip.user_ns \ or identifier in ip.user_global_ns \ or identifier in ip.ns_table['builtin']\ or iskeyword(identifier))
#-----------------------------------------------------------------------------# Main Prefilter manager#-----------------------------------------------------------------------------
class PrefilterManager(Configurable): """Main prefilter component.
The IPython prefilter is run on all user input before it is run. The prefilter consumes lines of input and produces transformed lines of input.
The implementation consists of two phases:
1. Transformers 2. Checkers and handlers
Over time, we plan on deprecating the checkers and handlers and doing everything in the transformers.
The transformers are instances of :class:`PrefilterTransformer` and have a single method :meth:`transform` that takes a line and returns a transformed line. The transformation can be accomplished using any tool, but our current ones use regular expressions for speed.
After all the transformers have been run, the line is fed to the checkers, which are instances of :class:`PrefilterChecker`. The line is passed to the :meth:`check` method, which either returns `None` or a :class:`PrefilterHandler` instance. If `None` is returned, the other checkers are tried. If an :class:`PrefilterHandler` instance is returned, the line is passed to the :meth:`handle` method of the returned handler and no further checkers are tried.
Both transformers and checkers have a `priority` attribute, that determines the order in which they are called. Smaller priorities are tried first.
Both transformers and checkers also have `enabled` attribute, which is a boolean that determines if the instance is used.
Users or developers can change the priority or enabled attribute of transformers or checkers, but they must call the :meth:`sort_checkers` or :meth:`sort_transformers` method after changing the priority. """
multi_line_specials = Bool(True).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs): super(PrefilterManager, self).__init__(shell=shell, **kwargs) self.shell = shell self._transformers = [] self.init_handlers() self.init_checkers()
#------------------------------------------------------------------------- # API for managing transformers #-------------------------------------------------------------------------
def sort_transformers(self): """Sort the transformers by priority.
This must be called after the priority of a transformer is changed. The :meth:`register_transformer` method calls this automatically. """ self._transformers.sort(key=lambda x: x.priority)
@property def transformers(self): """Return a list of checkers, sorted by priority.""" return self._transformers
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
#------------------------------------------------------------------------- # API for managing checkers #-------------------------------------------------------------------------
def init_checkers(self): """Create the default checkers.""" self._checkers = [] for checker in _default_checkers: checker( shell=self.shell, prefilter_manager=self, parent=self )
def sort_checkers(self): """Sort the checkers by priority.
This must be called after the priority of a checker is changed. The :meth:`register_checker` method calls this automatically. """ self._checkers.sort(key=lambda x: x.priority)
@property def checkers(self): """Return a list of checkers, sorted by priority.""" return self._checkers
def register_checker(self, checker): """Register a checker instance.""" if checker not in self._checkers: self._checkers.append(checker) self.sort_checkers()
def unregister_checker(self, checker): """Unregister a checker instance.""" if checker in self._checkers: self._checkers.remove(checker)
#------------------------------------------------------------------------- # API for managing handlers #-------------------------------------------------------------------------
def init_handlers(self): """Create the default handlers.""" self._handlers = {} self._esc_handlers = {} for handler in _default_handlers: handler( shell=self.shell, prefilter_manager=self, parent=self )
@property def handlers(self): """Return a dict of all the handlers.""" return self._handlers
def register_handler(self, name, handler, esc_strings): """Register a handler instance by name with esc_strings.""" self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
def unregister_handler(self, name, handler, esc_strings): """Unregister a handler instance by name with esc_strings.""" try: del self._handlers[name] except KeyError: pass for esc_str in esc_strings: h = self._esc_handlers.get(esc_str) if h is handler: del self._esc_handlers[esc_str]
def get_handler_by_name(self, name): """Get a handler by its name.""" return self._handlers.get(name)
def get_handler_by_esc(self, esc_str): """Get a handler by its escape string.""" return self._esc_handlers.get(esc_str)
#------------------------------------------------------------------------- # Main prefiltering API #-------------------------------------------------------------------------
def prefilter_line_info(self, line_info): """Prefilter a line that has been converted to a LineInfo object.
This implements the checker/handler part of the prefilter pipe. """ # print("prefilter_line_info: ", line_info) handler = self.find_handler(line_info) return handler.handle(line_info)
def find_handler(self, line_info): """Find a handler for the line_info by trying checkers.""" for checker in self.checkers: if checker.enabled: handler = checker.check(line_info) if handler: return handler return self.get_handler_by_name('normal')
def transform_line(self, line, continue_prompt): """Calls the enabled transformers in order of increasing priority.""" for transformer in self.transformers: if transformer.enabled: line = transformer.transform(line, continue_prompt) return line
def prefilter_line(self, line, continue_prompt=False): """Prefilter a single input line as text.
This method prefilters a single line of text by calling the transformers and then the checkers/handlers. """
# print("prefilter_line: ", line, continue_prompt) # All handlers *must* return a value, even if it's blank ('').
# save the line away in case we crash, so the post-mortem handler can # record it self.shell._last_input_line = line
if not line: # Return immediately on purely empty lines, so that if the user # previously typed some whitespace that started a continuation # prompt, he can break out of that loop with just an empty line. # This is how the default python prompt works. return ''
# At this point, we invoke our transformers. if not continue_prompt or (continue_prompt and self.multi_line_specials): line = self.transform_line(line, continue_prompt)
# Now we compute line_info for the checkers and handlers line_info = LineInfo(line, continue_prompt)
# the input history needs to track even empty lines stripped = line.strip()
normal_handler = self.get_handler_by_name('normal') if not stripped: return normal_handler.handle(line_info)
# special handlers are only allowed for single line statements if continue_prompt and not self.multi_line_specials: return normal_handler.handle(line_info)
prefiltered = self.prefilter_line_info(line_info) # print("prefiltered line: %r" % prefiltered) return prefiltered
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text.
This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input.
This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter. """ llines = lines.rstrip('\n').split('\n') # We can get multiple lines in one shot, where multiline input 'blends' # into one line, in cases like recalling from the readline history # buffer. We need to make sure that in such cases, we correctly # communicate downstream which line is first and which are continuation # ones. if len(llines) > 1: out = '\n'.join([self.prefilter_line(line, lnum>0) for lnum, line in enumerate(llines) ]) else: out = self.prefilter_line(llines[0], continue_prompt)
return out
#-----------------------------------------------------------------------------# Prefilter transformers#-----------------------------------------------------------------------------
class PrefilterTransformer(Configurable): """Transform a line of user input."""
priority = Integer(100).tag(config=True) # Transformers don't currently use shell or prefilter_manager, but as we # move away from checkers and handlers, they will need them. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) enabled = Bool(True).tag(config=True)
def __init__(self, shell=None, prefilter_manager=None, **kwargs): super(PrefilterTransformer, self).__init__( shell=shell, prefilter_manager=prefilter_manager, **kwargs ) self.prefilter_manager.register_transformer(self)
def transform(self, line, continue_prompt): """Transform a line, returning the new one.""" return None
def __repr__(self): return "<%s(priority=%r, enabled=%r)>" % ( self.__class__.__name__, self.priority, self.enabled)
#-----------------------------------------------------------------------------# Prefilter checkers#-----------------------------------------------------------------------------
class PrefilterChecker(Configurable): """Inspect an input line and return a handler for that line."""
priority = Integer(100).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) enabled = Bool(True).tag(config=True)
def __init__(self, shell=None, prefilter_manager=None, **kwargs): super(PrefilterChecker, self).__init__( shell=shell, prefilter_manager=prefilter_manager, **kwargs ) self.prefilter_manager.register_checker(self)
def check(self, line_info): """Inspect line_info and return a handler instance or None.""" return None
def __repr__(self): return "<%s(priority=%r, enabled=%r)>" % ( self.__class__.__name__, self.priority, self.enabled)
class EmacsChecker(PrefilterChecker):
priority = Integer(100).tag(config=True) enabled = Bool(False).tag(config=True)
def check(self, line_info): "Emacs ipython-mode tags certain input lines." if line_info.line.endswith('# PYTHON-MODE'): return self.prefilter_manager.get_handler_by_name('emacs') else: return None
class MacroChecker(PrefilterChecker):
priority = Integer(250).tag(config=True)
def check(self, line_info): obj = self.shell.user_ns.get(line_info.ifun) if isinstance(obj, Macro): return self.prefilter_manager.get_handler_by_name('macro') else: return None
class IPyAutocallChecker(PrefilterChecker):
priority = Integer(300).tag(config=True)
def check(self, line_info): "Instances of IPyAutocall in user_ns get autocalled immediately" obj = self.shell.user_ns.get(line_info.ifun, None) if isinstance(obj, IPyAutocall): obj.set_ip(self.shell) return self.prefilter_manager.get_handler_by_name('auto') else: return None
class AssignmentChecker(PrefilterChecker):
priority = Integer(600).tag(config=True)
def check(self, line_info): """Check to see if user is assigning to a var for the first time, in which case we want to avoid any sort of automagic / autocall games.
This allows users to assign to either alias or magic names true python variables (the magic/alias systems always take second seat to true python code). E.g. ls='hi', or ls,that=1,2""" if line_info.the_rest: if line_info.the_rest[0] in '=,': return self.prefilter_manager.get_handler_by_name('normal') else: return None
class AutoMagicChecker(PrefilterChecker):
priority = Integer(700).tag(config=True)
def check(self, line_info): """If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could shadow it.""" if not self.shell.automagic or not self.shell.find_magic(line_info.ifun): return None
# We have a likely magic method. Make sure we should actually call it. if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: return None
head = line_info.ifun.split('.',1)[0] if is_shadowed(head, self.shell): return None
return self.prefilter_manager.get_handler_by_name('magic')
class PythonOpsChecker(PrefilterChecker):
priority = Integer(900).tag(config=True)
def check(self, line_info): """If the 'rest' of the line begins with a function call or pretty much any python operator, we should simply execute the line (regardless of whether or not there's a possible autocall expansion). This avoids spurious (and very confusing) geattr() accesses.""" if line_info.the_rest and line_info.the_rest[0] in "!=()<>,+*/%^&|": return self.prefilter_manager.get_handler_by_name("normal") else: return None
class AutocallChecker(PrefilterChecker):
priority = Integer(1000).tag(config=True)
function_name_regexp = CRegExp(re_fun_name, help="RegExp to identify potential function names." ).tag(config=True) exclude_regexp = CRegExp(re_exclude_auto, help="RegExp to exclude strings with this start from autocalling." ).tag(config=True)
def check(self, line_info): "Check if the initial word/function is callable and autocall is on." if not self.shell.autocall: return None
oinfo = self.shell._ofind(line_info.ifun) # This can mutate state via getattr if not oinfo.found: return None
ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf'] ifun = line_info.ifun line = line_info.line if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')): return None
if ( callable(oinfo.obj) and (not self.exclude_regexp.match(line_info.the_rest)) and self.function_name_regexp.match(line_info.ifun) and ( line_info.raw_the_rest.startswith(" ") or not line_info.raw_the_rest.strip() ) ): return self.prefilter_manager.get_handler_by_name("auto") else: return None
#-----------------------------------------------------------------------------# Prefilter handlers#-----------------------------------------------------------------------------
class PrefilterHandler(Configurable): handler_name = Unicode("normal") esc_strings: List = List([]) shell = Instance( "IPython.core.interactiveshell.InteractiveShellABC", allow_none=True ) prefilter_manager = Instance( "IPython.core.prefilter.PrefilterManager", allow_none=True )
def __init__(self, shell=None, prefilter_manager=None, **kwargs): super(PrefilterHandler, self).__init__( shell=shell, prefilter_manager=prefilter_manager, **kwargs ) self.prefilter_manager.register_handler( self.handler_name, self, self.esc_strings )
def handle(self, line_info): # print("normal: ", line_info) """Handle normal input lines. Use as a template for handlers."""
# With autoindent on, we need some way to exit the input loop, and I # don't want to force the user to have to backspace all the way to # clear the line. The rule will be in this case, that either two # lines of pure whitespace in a row, or a line of pure whitespace but # of a size different to the indent level, will exit the input loop. line = line_info.line continue_prompt = line_info.continue_prompt
if (continue_prompt and self.shell.autoindent and line.isspace() and 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): line = ''
return line
def __str__(self): return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
class MacroHandler(PrefilterHandler): handler_name = Unicode("macro")
def handle(self, line_info): obj = self.shell.user_ns.get(line_info.ifun) pre_space = line_info.pre_whitespace line_sep = "\n" + pre_space return pre_space + line_sep.join(obj.value.splitlines())
class MagicHandler(PrefilterHandler):
handler_name = Unicode('magic') esc_strings = List([ESC_MAGIC])
def handle(self, line_info): """Execute magic functions.""" ifun = line_info.ifun the_rest = line_info.the_rest #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args) t_arg_s = ifun + " " + the_rest t_magic_name, _, t_magic_arg_s = t_arg_s.partition(' ') t_magic_name = t_magic_name.lstrip(ESC_MAGIC) cmd = '%sget_ipython().run_line_magic(%r, %r)' % (line_info.pre_whitespace, t_magic_name, t_magic_arg_s) return cmd
class AutoHandler(PrefilterHandler):
handler_name = Unicode('auto') esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
def handle(self, line_info): """Handle lines which can be auto-executed, quoting if requested.""" line = line_info.line ifun = line_info.ifun the_rest = line_info.the_rest esc = line_info.esc continue_prompt = line_info.continue_prompt obj = self.shell._ofind(line_info.ifun).obj
# This should only be active for single-line input! if continue_prompt: return line
force_auto = isinstance(obj, IPyAutocall)
# User objects sometimes raise exceptions on attribute access other # than AttributeError (we've seen it in the past), so it's safest to be # ultra-conservative here and catch all. try: auto_rewrite = obj.rewrite except Exception: auto_rewrite = True
if esc == ESC_QUOTE: # Auto-quote splitting on whitespace newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) elif esc == ESC_QUOTE2: # Auto-quote whole string newcmd = '%s("%s")' % (ifun,the_rest) elif esc == ESC_PAREN: newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) else: # Auto-paren. if force_auto: # Don't rewrite if it is already a call. do_rewrite = not the_rest.startswith('(') else: if not the_rest: # We only apply it to argument-less calls if the autocall # parameter is set to 2. do_rewrite = (self.shell.autocall >= 2) elif the_rest.startswith('[') and hasattr(obj, '__getitem__'): # Don't autocall in this case: item access for an object # which is BOTH callable and implements __getitem__. do_rewrite = False else: do_rewrite = True
# Figure out the rewritten command if do_rewrite: if the_rest.endswith(';'): newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) else: newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) else: normal_handler = self.prefilter_manager.get_handler_by_name('normal') return normal_handler.handle(line_info)
# Display the rewritten call if auto_rewrite: self.shell.auto_rewrite_input(newcmd)
return newcmd
class EmacsHandler(PrefilterHandler):
handler_name = Unicode('emacs') esc_strings = List([])
def handle(self, line_info): """Handle input lines marked by python-mode."""
# Currently, nothing is done. Later more functionality can be added # here if needed.
# The input cache shouldn't be updated return line_info.line
#-----------------------------------------------------------------------------# Defaults#-----------------------------------------------------------------------------
_default_checkers = [ EmacsChecker, MacroChecker, IPyAutocallChecker, AssignmentChecker, AutoMagicChecker, PythonOpsChecker, AutocallChecker]
_default_handlers = [ PrefilterHandler, MacroHandler, MagicHandler, AutoHandler, EmacsHandler]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315# encoding: utf-8"""An application for managing IPython profiles.
To be invoked as the `ipython profile` subcommand.
Authors:
* Min RK
"""
#-----------------------------------------------------------------------------# Copyright (C) 2008 The IPython Development Team## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------
import os
from traitlets.config.application import Applicationfrom IPython.core.application import ( BaseIPythonApplication, base_flags)from IPython.core.profiledir import ProfileDirfrom IPython.utils.importstring import import_itemfrom IPython.paths import get_ipython_dir, get_ipython_package_dirfrom traitlets import Unicode, Bool, Dict, observe
#-----------------------------------------------------------------------------# Constants#-----------------------------------------------------------------------------
create_help = """Create an IPython profile by name
Create an ipython profile directory by its name orprofile directory path. Profile directories containconfiguration, log and security related files and are namedusing the convention 'profile_<name>'. By default they arelocated in your ipython directory. Once created, you willcan edit the configuration files in the profiledirectory to configure IPython. Most users will create aprofile directory by name,`ipython profile create myprofile`, which will put the directoryin `<ipython_dir>/profile_myprofile`."""list_help = """List available IPython profiles
List all available profiles, by profile location, that canbe found in the current working directly or in the ipythondirectory. Profile directories are named using the convention'profile_<profile>'."""profile_help = """Manage IPython profiles
Profile directories containconfiguration, log and security related files and are namedusing the convention 'profile_<name>'. By default they arelocated in your ipython directory. You can create profileswith `ipython profile create <name>`, or see the profiles youalready have with `ipython profile list`
To get started configuring IPython, simply do:
$> ipython profile create
and IPython will create the default profile in <ipython_dir>/profile_default,where you can edit ipython_config.py to start configuring IPython.
"""
_list_examples = "ipython profile list # list all profiles"
_create_examples = """ipython profile create foo # create profile foo w/ default config filesipython profile create foo --reset # restage default config files over currentipython profile create foo --parallel # also stage parallel config files"""
_main_examples = """ipython profile create -h # show the help string for the create subcommandipython profile list -h # show the help string for the list subcommand
ipython locate profile foo # print the path to the directory for profile 'foo'"""
#-----------------------------------------------------------------------------# Profile Application Class (for `ipython profile` subcommand)#-----------------------------------------------------------------------------
def list_profiles_in(path): """list profiles in a given root directory""" profiles = []
# for python 3.6+ rewrite to: with os.scandir(path) as dirlist: files = os.scandir(path) for f in files: if f.is_dir() and f.name.startswith('profile_'): profiles.append(f.name.split('_', 1)[-1]) return profiles
def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'core', u'profile') profiles = []
# for python 3.6+ rewrite to: with os.scandir(path) as dirlist: files = os.scandir(path) for profile in files: if profile.is_dir() and profile.name != "__pycache__": profiles.append(profile.name) return profiles
class ProfileLocate(BaseIPythonApplication): description = """print the path to an IPython profile dir""" def parse_command_line(self, argv=None): super(ProfileLocate, self).parse_command_line(argv) if self.extra_args: self.profile = self.extra_args[0] def start(self): print(self.profile_dir.location)
class ProfileList(Application): name = u'ipython-profile' description = list_help examples = _list_examples
aliases = Dict({ 'ipython-dir' : 'ProfileList.ipython_dir', 'log-level' : 'Application.log_level', }) flags = Dict(dict( debug = ({'Application' : {'log_level' : 0}}, "Set Application.log_level to 0, maximizing log output." ) ))
ipython_dir = Unicode(get_ipython_dir(), help=""" The name of the IPython directory. This directory is used for logging configuration (through profiles), history storage, etc. The default is usually $HOME/.ipython. This options can also be specified through the environment variable IPYTHONDIR. """ ).tag(config=True)
def _print_profiles(self, profiles): """print list of profiles, indented.""" for profile in profiles: print(' %s' % profile)
def list_profile_dirs(self): profiles = list_bundled_profiles() if profiles: print() print("Available profiles in IPython:") self._print_profiles(profiles) print() print(" The first request for a bundled profile will copy it") print(" into your IPython directory (%s)," % self.ipython_dir) print(" where you can customize it.") profiles = list_profiles_in(self.ipython_dir) if profiles: print() print("Available profiles in %s:" % self.ipython_dir) self._print_profiles(profiles) profiles = list_profiles_in(os.getcwd()) if profiles: print() print( "Profiles from CWD have been removed for security reason, see CVE-2022-21699:" )
print() print("To use any of the above profiles, start IPython with:") print(" ipython --profile=<name>") print()
def start(self): self.list_profile_dirs()
create_flags = {}create_flags.update(base_flags)# don't include '--init' flag, which implies running profile create in other appscreate_flags.pop('init')create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}}, "reset config files in this profile to the defaults.")create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}}, "Include the config files for parallel " "computing apps (ipengine, ipcontroller, etc.)")
class ProfileCreate(BaseIPythonApplication): name = u'ipython-profile' description = create_help examples = _create_examples auto_create = Bool(True).tag(config=True) def _log_format_default(self): return "[%(name)s] %(message)s"
def _copy_config_files_default(self): return True
parallel = Bool(False, help="whether to include parallel computing config files" ).tag(config=True)
@observe('parallel') def _parallel_changed(self, change): parallel_files = [ 'ipcontroller_config.py', 'ipengine_config.py', 'ipcluster_config.py' ] if change['new']: for cf in parallel_files: self.config_files.append(cf) else: for cf in parallel_files: if cf in self.config_files: self.config_files.remove(cf)
def parse_command_line(self, argv): super(ProfileCreate, self).parse_command_line(argv) # accept positional arg as profile name if self.extra_args: self.profile = self.extra_args[0]
flags = Dict(create_flags)
classes = [ProfileDir] def _import_app(self, app_path): """import an app class""" app = None name = app_path.rsplit('.', 1)[-1] try: app = import_item(app_path) except ImportError: self.log.info("Couldn't import %s, config file will be excluded", name) except Exception: self.log.warning('Unexpected error importing %s', name, exc_info=True) return app
def init_config_files(self): super(ProfileCreate, self).init_config_files() # use local imports, since these classes may import from here from IPython.terminal.ipapp import TerminalIPythonApp apps = [TerminalIPythonApp] for app_path in ( 'ipykernel.kernelapp.IPKernelApp', ): app = self._import_app(app_path) if app is not None: apps.append(app) if self.parallel: from ipyparallel.apps.ipcontrollerapp import IPControllerApp from ipyparallel.apps.ipengineapp import IPEngineApp from ipyparallel.apps.ipclusterapp import IPClusterStart apps.extend([ IPControllerApp, IPEngineApp, IPClusterStart, ]) for App in apps: app = App() app.config.update(self.config) app.log = self.log app.overwrite = self.overwrite app.copy_config_files=True app.ipython_dir=self.ipython_dir app.profile_dir=self.profile_dir app.init_config_files()
def stage_default_config_file(self): pass
class ProfileApp(Application): name = u'ipython profile' description = profile_help examples = _main_examples
subcommands = Dict(dict( create = (ProfileCreate, ProfileCreate.description.splitlines()[0]), list = (ProfileList, ProfileList.description.splitlines()[0]), locate = (ProfileLocate, ProfileLocate.description.splitlines()[0]), ))
def start(self): if self.subapp is None: print( "No subcommand specified. Must specify one of: " + ", ".join(map(repr, self.subcommands)) + ".\n" ) self.print_description() self.print_subcommands() self.exit(1) else: return self.subapp.start()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244# encoding: utf-8"""An object for managing IPython profile directories."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import osimport shutilimport errnofrom pathlib import Path
from traitlets.config.configurable import LoggingConfigurablefrom ..paths import get_ipython_package_dirfrom ..utils.path import expand_path, ensure_dir_existsfrom traitlets import Unicode, Bool, observe
from typing import Optional
#-----------------------------------------------------------------------------# Module errors#-----------------------------------------------------------------------------
class ProfileDirError(Exception): pass
#-----------------------------------------------------------------------------# Class for managing profile directories#-----------------------------------------------------------------------------
class ProfileDir(LoggingConfigurable): """An object to manage the profile directory and its resources.
The profile directory is used by all IPython applications, to manage configuration, logging and security.
This object knows how to find, create and manage these directories. This should be used by any code that wants to handle profiles. """
security_dir_name = Unicode('security') log_dir_name = Unicode('log') startup_dir_name = Unicode('startup') pid_dir_name = Unicode('pid') static_dir_name = Unicode('static') security_dir = Unicode(u'') log_dir = Unicode(u'') startup_dir = Unicode(u'') pid_dir = Unicode(u'') static_dir = Unicode(u'')
location = Unicode(u'', help="""Set the profile location directly. This overrides the logic used by the `profile` option.""", ).tag(config=True)
_location_isset = Bool(False) # flag for detecting multiply set location @observe('location') def _location_changed(self, change): if self._location_isset: raise RuntimeError("Cannot set profile location more than once.") self._location_isset = True new = change['new'] ensure_dir_exists(new)
# ensure config files exist: self.security_dir = os.path.join(new, self.security_dir_name) self.log_dir = os.path.join(new, self.log_dir_name) self.startup_dir = os.path.join(new, self.startup_dir_name) self.pid_dir = os.path.join(new, self.pid_dir_name) self.static_dir = os.path.join(new, self.static_dir_name) self.check_dirs()
def _mkdir(self, path: str, mode: Optional[int] = None) -> bool: """ensure a directory exists at a given path
This is a version of os.mkdir, with the following differences:
- returns whether the directory has been created or not. - ignores EEXIST, protecting against race conditions where the dir may have been created in between the check and the creation - sets permissions if requested and the dir already exists
Parameters ---------- path: str path of the dir to create mode: int see `mode` of `os.mkdir`
Returns ------- bool: returns True if it created the directory, False otherwise """
if os.path.exists(path): if mode and os.stat(path).st_mode != mode: try: os.chmod(path, mode) except OSError: self.log.warning( "Could not set permissions on %s", path ) return False try: if mode: os.mkdir(path, mode) else: os.mkdir(path) except OSError as e: if e.errno == errno.EEXIST: return False else: raise
return True @observe('log_dir') def check_log_dir(self, change=None): self._mkdir(self.log_dir) @observe('startup_dir') def check_startup_dir(self, change=None): if self._mkdir(self.startup_dir): readme = os.path.join(self.startup_dir, "README") src = os.path.join( get_ipython_package_dir(), "core", "profile", "README_STARTUP" )
if os.path.exists(src): if not os.path.exists(readme): shutil.copy(src, readme) else: self.log.warning( "Could not copy README_STARTUP to startup dir. Source file %s does not exist.", src, )
@observe('security_dir') def check_security_dir(self, change=None): self._mkdir(self.security_dir, 0o40700)
@observe('pid_dir') def check_pid_dir(self, change=None): self._mkdir(self.pid_dir, 0o40700)
def check_dirs(self): self.check_security_dir() self.check_log_dir() self.check_pid_dir() self.check_startup_dir()
def copy_config_file(self, config_file: str, path: Path, overwrite=False) -> bool: """Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.core.profile`. This function moves these from that location to the working profile directory. """ dst = Path(os.path.join(self.location, config_file)) if dst.exists() and not overwrite: return False if path is None: path = os.path.join(get_ipython_package_dir(), u'core', u'profile', u'default') assert isinstance(path, Path) src = path / config_file shutil.copy(src, dst) return True
@classmethod def create_profile_dir(cls, profile_dir, config=None): """Create a new profile directory given a full path.
Parameters ---------- profile_dir : str The full path to the profile directory. If it does exist, it will be used. If not, it will be created. """ return cls(location=profile_dir, config=config)
@classmethod def create_profile_dir_by_name(cls, path, name=u'default', config=None): """Create a profile dir by profile name and path.
Parameters ---------- path : unicode The path (directory) to put the profile directory in. name : unicode The name of the profile. The name of the profile directory will be "profile_<profile>". """ if not os.path.isdir(path): raise ProfileDirError('Directory not found: %s' % path) profile_dir = os.path.join(path, u'profile_' + name) return cls(location=profile_dir, config=config)
@classmethod def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None): """Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it is not found, a :class:`ProfileDirError` exception will be raised.
The search path algorithm is: 1. ``os.getcwd()`` # removed for security reason. 2. ``ipython_dir``
Parameters ---------- ipython_dir : unicode or str The IPython directory to use. name : unicode or str The name of the profile. The name of the profile directory will be "profile_<profile>". """ dirname = u'profile_' + name paths = [ipython_dir] for p in paths: profile_dir = os.path.join(p, dirname) if os.path.isdir(profile_dir): return cls(location=profile_dir, config=config) else: raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
@classmethod def find_profile_dir(cls, profile_dir, config=None): """Find/create a profile dir and return its ProfileDir.
This will create the profile directory if it doesn't exist.
Parameters ---------- profile_dir : unicode or str The path of the profile directory. """ profile_dir = expand_path(profile_dir) if not os.path.isdir(profile_dir): raise ProfileDirError('Profile directory not found: %s' % profile_dir) return cls(location=profile_dir, config=config)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514# -*- coding: utf-8 -*-"""Pylab (matplotlib) support utilities."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
from io import BytesIOfrom binascii import b2a_base64from functools import partialimport warnings
from IPython.core.display import _pngxyfrom IPython.utils.decorators import flag_calls
# Matplotlib backend resolution functionality moved from IPython to Matplotlib# in IPython 8.24 and Matplotlib 3.9.0. Need to keep `backends` and `backend2gui`# here for earlier Matplotlib and for external backend libraries such as# mplcairo that might rely upon it._deprecated_backends = { "tk": "TkAgg", "gtk": "GTKAgg", "gtk3": "GTK3Agg", "gtk4": "GTK4Agg", "wx": "WXAgg", "qt4": "Qt4Agg", "qt5": "Qt5Agg", "qt6": "QtAgg", "qt": "QtAgg", "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",}
# We also need a reverse backends2guis mapping that will properly choose which# GUI support to activate based on the desired matplotlib backend. For the# most part it's just a reverse of the above dict, but we also need to add a# few others that map to the same GUI manually:_deprecated_backend2gui = dict( zip(_deprecated_backends.values(), _deprecated_backends.keys()))# In the reverse mapping, there are a few extra valid matplotlib backends that# map to the same GUI support_deprecated_backend2gui["GTK"] = _deprecated_backend2gui["GTKCairo"] = "gtk"_deprecated_backend2gui["GTK3Cairo"] = "gtk3"_deprecated_backend2gui["GTK4Cairo"] = "gtk4"_deprecated_backend2gui["WX"] = "wx"_deprecated_backend2gui["CocoaAgg"] = "osx"# There needs to be a hysteresis here as the new QtAgg Matplotlib backend# supports either Qt5 or Qt6 and the IPython qt event loop support Qt4, Qt5,# and Qt6._deprecated_backend2gui["QtAgg"] = "qt"_deprecated_backend2gui["Qt4Agg"] = "qt4"_deprecated_backend2gui["Qt5Agg"] = "qt5"
# And some backends that don't need GUI integrationdel _deprecated_backend2gui["nbAgg"]del _deprecated_backend2gui["agg"]del _deprecated_backend2gui["svg"]del _deprecated_backend2gui["pdf"]del _deprecated_backend2gui["ps"]del _deprecated_backend2gui["module://matplotlib_inline.backend_inline"]del _deprecated_backend2gui["module://ipympl.backend_nbagg"]
# Deprecated attributes backends and backend2gui mostly following PEP 562.def __getattr__(name): if name in ("backends", "backend2gui"): warnings.warn( f"{name} is deprecated since IPython 8.24, backends are managed " "in matplotlib and can be externally registered.", DeprecationWarning, ) return globals()[f"_deprecated_{name}"] raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
#-----------------------------------------------------------------------------# Matplotlib utilities#-----------------------------------------------------------------------------
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]
def print_figure(fig, fmt="png", bbox_inches="tight", base64=False, **kwargs): """Print a figure to an image, and return the resulting file data
Returned data will be bytes unless ``fmt='svg'``, in which case it will be unicode.
Any keyword args are passed to fig.canvas.print_figure, such as ``quality`` or ``bbox_inches``.
If `base64` is True, return base64-encoded str instead of raw bytes for binary-encoded image formats
.. versionadded:: 7.29 base64 argument """ # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return
dpi = fig.dpi if fmt == 'retina': dpi = dpi * 2 fmt = 'png'
# build keyword args kw = { "format":fmt, "facecolor":fig.get_facecolor(), "edgecolor":fig.get_edgecolor(), "dpi":dpi, "bbox_inches":bbox_inches, } # **kwargs get higher priority kw.update(kwargs)
bytes_io = BytesIO() if fig.canvas is None: from matplotlib.backend_bases import FigureCanvasBase FigureCanvasBase(fig)
fig.canvas.print_figure(bytes_io, **kw) data = bytes_io.getvalue() if fmt == 'svg': data = data.decode('utf-8') elif base64: data = b2a_base64(data, newline=False).decode("ascii") return data
def retina_figure(fig, base64=False, **kwargs): """format a figure as a pixel-doubled (retina) PNG
If `base64` is True, return base64-encoded str instead of raw bytes for binary-encoded image formats
.. versionadded:: 7.29 base64 argument """ pngdata = print_figure(fig, fmt="retina", base64=False, **kwargs) # Make sure that retina_figure acts just like print_figure and returns # None when the figure is empty. if pngdata is None: return w, h = _pngxy(pngdata) metadata = {"width": w//2, "height":h//2} if base64: pngdata = b2a_base64(pngdata, newline=False).decode("ascii") return pngdata, metadata
# We need a little factory function here to create the closure where# safe_execfile can live.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 with matplotlib.rc_context({"interactive": False}): safe_execfile(fname, *where, **kw)
if matplotlib.is_interactive(): plt.show()
# 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
def _reshow_nbagg_figure(fig): """reshow an nbagg figure""" try: reshow = fig.canvas.manager.reshow except AttributeError as e: raise NotImplementedError() from e else: reshow()
def select_figure_formats(shell, formats, **kwargs): """Select figure formats for the inline backend.
Parameters ---------- shell : InteractiveShell The main IPython instance. formats : str or set One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. **kwargs : any Extra keyword arguments to be passed to fig.canvas.print_figure. """ import matplotlib from matplotlib.figure import Figure
svg_formatter = shell.display_formatter.formatters['image/svg+xml'] png_formatter = shell.display_formatter.formatters['image/png'] jpg_formatter = shell.display_formatter.formatters['image/jpeg'] pdf_formatter = shell.display_formatter.formatters['application/pdf']
if isinstance(formats, str): formats = {formats} # cast in case of list / tuple formats = set(formats)
[ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ] mplbackend = matplotlib.get_backend().lower() if mplbackend in ("nbagg", "ipympl", "widget", "module://ipympl.backend_nbagg"): formatter = shell.display_formatter.ipython_display_formatter formatter.for_type(Figure, _reshow_nbagg_figure)
supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'} bad = formats.difference(supported) if bad: bs = "%s" % ','.join([repr(f) for f in bad]) gs = "%s" % ','.join([repr(f) for f in supported]) raise ValueError("supported formats are: %s not %s" % (gs, bs))
if "png" in formats: png_formatter.for_type( Figure, partial(print_figure, fmt="png", base64=True, **kwargs) ) if "retina" in formats or "png2x" in formats: png_formatter.for_type(Figure, partial(retina_figure, base64=True, **kwargs)) if "jpg" in formats or "jpeg" in formats: jpg_formatter.for_type( Figure, partial(print_figure, fmt="jpg", base64=True, **kwargs) ) if "svg" in formats: svg_formatter.for_type(Figure, partial(print_figure, fmt="svg", **kwargs)) if "pdf" in formats: pdf_formatter.for_type( Figure, partial(print_figure, fmt="pdf", base64=True, **kwargs) )
#-----------------------------------------------------------------------------# Code for initializing matplotlib and importing pylab#-----------------------------------------------------------------------------
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 _matplotlib_manages_backends(): backend_registry = matplotlib.backends.registry.backend_registry
# gui argument may be a gui event loop or may be a backend name. if gui in ("auto", None): backend = matplotlib.rcParamsOrig["backend"] backend, gui = backend_registry.resolve_backend(backend) else: gui = _convert_gui_to_matplotlib(gui) backend, gui = backend_registry.resolve_gui_or_backend(gui)
gui = _convert_gui_from_matplotlib(gui) return gui, backend
# Fallback to previous behaviour (Matplotlib < 3.9) mpl_version_info = getattr(matplotlib, "__version_info__", (0, 0)) has_unified_qt_backend = mpl_version_info >= (3, 5)
backends_ = dict(_deprecated_backends) if not has_unified_qt_backend: backends_["qt"] = "qt5agg"
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 = _deprecated_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]
# Matplotlib before _matplotlib_manages_backends() can return "inline" for # no gui event loop rather than the None that IPython >= 8.24.0 expects. if gui == "inline": gui = None
return gui, backend
def activate_matplotlib(backend): """Activate the given backend and set interactive to True."""
import matplotlib matplotlib.interactive(True)
# Matplotlib had a bug where even switch_backend could not force # the rcParam to update. This needs to be set *before* the module # magic of switch_backend(). matplotlib.rcParams['backend'] = backend
# Due to circular imports, pyplot may be only partially initialised # when this function runs. # So avoid needing matplotlib attribute-lookup to access pyplot. from matplotlib import pyplot as plt
plt.switch_backend(backend)
plt.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
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
# Determine if Matplotlib manages backends only if needed, and cache result.# Do not read this directly, instead use _matplotlib_manages_backends()._matplotlib_manages_backends_value: bool | None = None
def _matplotlib_manages_backends() -> bool: """Return True if Matplotlib manages backends, False otherwise.
If it returns True, the caller can be sure that matplotlib.backends.registry.backend_registry is available along with member functions resolve_gui_or_backend, resolve_backend, list_all, and list_gui_frameworks.
This function can be removed as it will always return True when Python 3.12, the latest version supported by Matplotlib < 3.9, reaches end-of-life in late 2028. """ global _matplotlib_manages_backends_value if _matplotlib_manages_backends_value is None: try: from matplotlib.backends.registry import backend_registry
_matplotlib_manages_backends_value = hasattr( backend_registry, "resolve_gui_or_backend" ) except ImportError: _matplotlib_manages_backends_value = False
return _matplotlib_manages_backends_value
def _list_matplotlib_backends_and_gui_loops() -> list[str]: """Return list of all Matplotlib backends and GUI event loops.
This is the list returned by %matplotlib --list """ if _matplotlib_manages_backends(): from matplotlib.backends.registry import backend_registry
ret = backend_registry.list_all() + [ _convert_gui_from_matplotlib(gui) for gui in backend_registry.list_gui_frameworks() ] else: from IPython.core import pylabtools
ret = list(pylabtools.backends.keys())
return sorted(["auto"] + ret)
# Matplotlib and IPython do not always use the same gui framework name.# Always use the appropriate one of these conversion functions when passing a# gui framework name to/from Matplotlib.def _convert_gui_to_matplotlib(gui: str | None) -> str | None: if gui and gui.lower() == "osx": return "macosx" return gui
def _convert_gui_from_matplotlib(gui: str | None) -> str | None: if gui and gui.lower() == "macosx": return "osx" return gui123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500# encoding: utf-8"""A mixin for :class:`~IPython.core.application.Application` classes thatlaunch InteractiveShell instances, load extensions, etc."""
# Copyright (c) IPython Development Team.# Distributed under the terms of the Modified BSD License.
import globfrom itertools import chainimport osimport sysimport typing as t
from traitlets.config.application import boolean_flagfrom traitlets.config.configurable import Configurablefrom traitlets.config.loader import Configfrom IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRSfrom IPython.utils.contexts import preserve_keysfrom IPython.utils.path import filefindfrom traitlets import ( Unicode, Instance, List, Bool, CaselessStrEnum, observe, DottedObjectName, Undefined,)from IPython.terminal import pt_inputhooks
# -----------------------------------------------------------------------------# Aliases and Flags# -----------------------------------------------------------------------------
gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
shell_flags = {}
addflag = lambda *args: shell_flags.update(boolean_flag(*args))addflag( "autoindent", "InteractiveShell.autoindent", "Turn on autoindenting.", "Turn off autoindenting.",)addflag( "automagic", "InteractiveShell.automagic", """Turn on the auto calling of magic commands. Type %%magic at the IPython prompt for more information.""", 'Turn off the auto calling of magic commands.')addflag('pdb', 'InteractiveShell.pdb', "Enable auto calling the pdb debugger after every exception.", "Disable auto calling the pdb debugger after every exception.")addflag('pprint', 'PlainTextFormatter.pprint', "Enable auto pretty printing of results.", "Disable auto pretty printing of results.")addflag('color-info', 'InteractiveShell.color_info', """IPython can display information about objects via a set of functions, and optionally can use colors for this, syntax highlighting source code and various other elements. This is on by default, but can cause problems with some pagers. If you see such problems, you can disable the colours.""", "Disable using colors for info related things.")addflag('ignore-cwd', 'InteractiveShellApp.ignore_cwd', "Exclude the current working directory from sys.path", "Include the current working directory in sys.path",)nosep_config = Config()nosep_config.InteractiveShell.separate_in = ''nosep_config.InteractiveShell.separate_out = ''nosep_config.InteractiveShell.separate_out2 = ''
shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")shell_flags['pylab'] = ( {'InteractiveShellApp' : {'pylab' : 'auto'}}, """Pre-load matplotlib and numpy for interactive use with the default matplotlib backend. The exact options available depend on what Matplotlib provides at runtime.""",)shell_flags['matplotlib'] = ( {'InteractiveShellApp' : {'matplotlib' : 'auto'}}, """Configure matplotlib for interactive use with the default matplotlib backend. The exact options available depend on what Matplotlib provides at runtime.""",)
# it's possible we don't want short aliases for *all* of these:shell_aliases = dict( autocall="InteractiveShell.autocall", colors="InteractiveShell.colors", theme="InteractiveShell.colors", logfile="InteractiveShell.logfile", logappend="InteractiveShell.logappend", c="InteractiveShellApp.code_to_run", m="InteractiveShellApp.module_to_run", ext="InteractiveShellApp.extra_extensions", gui='InteractiveShellApp.gui', pylab='InteractiveShellApp.pylab', matplotlib='InteractiveShellApp.matplotlib',)shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
# -----------------------------------------------------------------------------# Traitlets# -----------------------------------------------------------------------------
class MatplotlibBackendCaselessStrEnum(CaselessStrEnum): """An enum of Matplotlib backend strings where the case should be ignored.
Prior to Matplotlib 3.9.0 the list of valid backends is hardcoded in pylabtools.backends. After that, Matplotlib manages backends.
The list of valid backends is determined when it is first needed to avoid wasting unnecessary initialisation time. """
def __init__( self: CaselessStrEnum[t.Any], default_value: t.Any = Undefined, **kwargs: t.Any, ) -> None: super().__init__(None, default_value=default_value, **kwargs)
def __getattribute__(self, name): if name == "values" and object.__getattribute__(self, name) is None: from IPython.core.pylabtools import _list_matplotlib_backends_and_gui_loops
self.values = _list_matplotlib_backends_and_gui_loops() return object.__getattribute__(self, name)
#-----------------------------------------------------------------------------# Main classes and functions#-----------------------------------------------------------------------------
class InteractiveShellApp(Configurable): """A Mixin for applications that start InteractiveShell instances.
Provides configurables for loading extensions and executing files as part of configuring a Shell environment.
The following methods should be called by the :meth:`initialize` method of the subclass:
- :meth:`init_path` - :meth:`init_shell` (to be implemented by the subclass) - :meth:`init_gui_pylab` - :meth:`init_extensions` - :meth:`init_code` """ extensions = List(Unicode(), help="A list of dotted module names of IPython extensions to load." ).tag(config=True)
extra_extensions = List( DottedObjectName(), help=""" Dotted module name(s) of one or more IPython extensions to load.
For specifying extra extensions to load on the command-line.
.. versionadded:: 7.10 """, ).tag(config=True)
reraise_ipython_extension_failures = Bool(False, help="Reraise exceptions encountered loading IPython extensions?", ).tag(config=True)
# Extensions that are always loaded (not configurable) default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
hide_initial_ns = Bool(True, help="""Should variables loaded at startup (by startup files, exec_lines, etc.) be hidden from tools like %who?""" ).tag(config=True)
exec_files = List(Unicode(), help="""List of files to run at IPython startup.""" ).tag(config=True) exec_PYTHONSTARTUP = Bool(True, help="""Run the file referenced by the PYTHONSTARTUP environment variable at IPython startup.""" ).tag(config=True) file_to_run = Unicode('', help="""A file to be run""").tag(config=True)
exec_lines = List(Unicode(), help="""lines of code to run at IPython startup.""" ).tag(config=True) code_to_run = Unicode("", help="Execute the given command string.").tag(config=True) module_to_run = Unicode("", help="Run the module as a script.").tag(config=True) gui = CaselessStrEnum( gui_keys, allow_none=True, help="Enable GUI event loop integration with any of {0}.".format(gui_keys), ).tag(config=True) matplotlib = MatplotlibBackendCaselessStrEnum( allow_none=True, help="""Configure matplotlib for interactive use with the default matplotlib backend. The exact options available depend on what Matplotlib provides at runtime.""", ).tag(config=True) pylab = MatplotlibBackendCaselessStrEnum( allow_none=True, help="""Pre-load matplotlib and numpy for interactive use, selecting a particular matplotlib backend and loop integration. The exact options available depend on what Matplotlib provides at runtime. """, ).tag(config=True) pylab_import_all = Bool( True, help="""If true, IPython will populate the user namespace with numpy, pylab, etc. and an ``import *`` is done from numpy and pylab, when using pylab mode.
When False, pylab mode should not import any names into the user namespace. """, ).tag(config=True) ignore_cwd = Bool( False, help="""If True, IPython will not add the current working directory to sys.path. When False, the current working directory is added to sys.path, allowing imports of modules defined in the current directory.""" ).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) # whether interact-loop should start interact = Bool(True)
user_ns = Instance(dict, args=None, allow_none=True) @observe('user_ns') def _user_ns_changed(self, change): if self.shell is not None: self.shell.user_ns = change['new'] self.shell.init_user_ns()
def init_path(self): """Add current working directory, '', to sys.path
Unless disabled by ignore_cwd config or sys.flags.safe_path.
Unlike Python's default, we insert before the first `site-packages` or `dist-packages` directory, so that it is after the standard library.
.. versionchanged:: 7.2 Try to insert after the standard library, instead of first. .. versionchanged:: 8.0 Allow optionally not including the current directory in sys.path .. versionchanged:: 9.7 Respect sys.flags.safe_path (PYTHONSAFEPATH and -P flag) """ if "" in sys.path or self.ignore_cwd or sys.flags.safe_path: return for idx, path in enumerate(sys.path): parent, last_part = os.path.split(path) if last_part in {'site-packages', 'dist-packages'}: break else: # no site-packages or dist-packages found (?!) # back to original behavior of inserting at the front idx = 0 sys.path.insert(idx, '')
def init_shell(self): raise NotImplementedError("Override in subclasses")
def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" enable = False shell = self.shell if self.pylab: enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all) key = self.pylab elif self.matplotlib: enable = shell.enable_matplotlib key = self.matplotlib elif self.gui: enable = shell.enable_gui key = self.gui
if not enable: return
try: r = enable(key) except ImportError: self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?") self.shell.showtraceback() return except Exception: self.log.warning("GUI event loop or pylab initialization failed") self.shell.showtraceback() return
if isinstance(r, tuple): gui, backend = r[:2] self.log.info("Enabling GUI event loop integration, " "eventloop=%s, matplotlib=%s", gui, backend) if key == "auto": print("Using matplotlib backend: %s" % backend) else: gui = r self.log.info("Enabling GUI event loop integration, " "eventloop=%s", gui)
def init_extensions(self): """Load all IPython extensions in IPythonApp.extensions.
This uses the :meth:`ExtensionManager.load_extensions` to load all the extensions listed in ``self.extensions``. """ try: self.log.debug("Loading IPython extensions...") extensions = ( self.default_extensions + self.extensions + self.extra_extensions ) for ext in extensions: try: self.log.info("Loading IPython extension: %s", ext) self.shell.extension_manager.load_extension(ext) except: if self.reraise_ipython_extension_failures: raise msg = ("Error in loading extension: {ext}\n" "Check your config files in {location}".format( ext=ext, location=self.profile_dir.location )) self.log.warning(msg, exc_info=True) except: if self.reraise_ipython_extension_failures: raise self.log.warning("Unknown error in loading extensions:", exc_info=True)
def init_code(self): """run the pre-flight code, specified via exec_lines""" self._run_startup_files() self._run_exec_lines() self._run_exec_files()
# Hide variables defined here from %who etc. if self.hide_initial_ns: self.shell.user_ns_hidden.update(self.shell.user_ns)
# command-line execution (ipython -i script.py, ipython -m module) # should *not* be excluded from %whos self._run_cmd_line_code() self._run_module()
# flush output, so itwon't be attached to the first cell sys.stdout.flush() sys.stderr.flush() self.shell._sys_modules_keys = set(sys.modules.keys())
def _run_exec_lines(self): """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" if not self.exec_lines: return try: self.log.debug("Running code from IPythonApp.exec_lines...") for line in self.exec_lines: try: self.log.info("Running code in user namespace: %s" % line) self.shell.run_cell(line, store_history=False) except: self.log.warning("Error in executing line in user " "namespace: %s" % line) self.shell.showtraceback() except: self.log.warning("Unknown error in handling IPythonApp.exec_lines:") self.shell.showtraceback()
def _exec_file(self, fname, shell_futures=False): try: full_filename = filefind(fname, [u'.', self.ipython_dir]) except IOError: self.log.warning("File not found: %r"%fname) return # Make sure that the running script gets a proper sys.argv as if it # were run from a system shell. save_argv = sys.argv sys.argv = [full_filename] + self.extra_args[1:] try: if os.path.isfile(full_filename): self.log.info("Running file in user namespace: %s" % full_filename) # Ensure that __file__ is always defined to match Python # behavior. with preserve_keys(self.shell.user_ns, '__file__'): self.shell.user_ns['__file__'] = fname if full_filename.endswith('.ipy') or full_filename.endswith('.ipynb'): self.shell.safe_execfile_ipy(full_filename, shell_futures=shell_futures) else: # default to python, even without extension self.shell.safe_execfile(full_filename, self.shell.user_ns, shell_futures=shell_futures, raise_exceptions=True) finally: sys.argv = save_argv
def _run_startup_files(self): """Run files from profile startup directory""" startup_dirs = [self.profile_dir.startup_dir] + [ os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS) ] startup_files = []
if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \ not (self.file_to_run or self.code_to_run or self.module_to_run): python_startup = os.environ['PYTHONSTARTUP'] self.log.debug("Running PYTHONSTARTUP file %s...", python_startup) try: self._exec_file(python_startup) except: self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup) self.shell.showtraceback() for startup_dir in startup_dirs[::-1]: startup_files += glob.glob(os.path.join(startup_dir, '*.py')) startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) if not startup_files: return
self.log.debug("Running startup files from %s...", startup_dir) try: for fname in sorted(startup_files): self._exec_file(fname) except: self.log.warning("Unknown error in handling startup files:") self.shell.showtraceback()
def _run_exec_files(self): """Run files from IPythonApp.exec_files""" if not self.exec_files: return
self.log.debug("Running files in IPythonApp.exec_files...") try: for fname in self.exec_files: self._exec_file(fname) except: self.log.warning("Unknown error in handling IPythonApp.exec_files:") self.shell.showtraceback()
def _run_cmd_line_code(self): """Run code or file specified at the command-line""" if self.code_to_run: line = self.code_to_run try: self.log.info("Running code given at command line (c=): %s" % line) self.shell.run_cell(line, store_history=False) except: self.log.warning("Error in executing line in user namespace: %s" % line) self.shell.showtraceback() if not self.interact: self.exit(1)
# Like Python itself, ignore the second if the first of these is present elif self.file_to_run: fname = self.file_to_run if os.path.isdir(fname): fname = os.path.join(fname, "__main__.py") if not os.path.exists(fname): self.log.warning("File '%s' doesn't exist", fname) if not self.interact: self.exit(2) try: self._exec_file(fname, shell_futures=True) except: self.shell.showtraceback(tb_offset=4) if not self.interact: self.exit(1)
def _run_module(self): """Run module specified at the command-line.""" if self.module_to_run: # Make sure that the module gets a proper sys.argv as if it were # run using `python -m`. save_argv = sys.argv sys.argv = [sys.executable] + self.extra_args try: self.shell.safe_run_module(self.module_to_run, self.shell.user_ns) finally: sys.argv = save_argv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Simple utility for splitting user input. This is used by both inputsplitter andprefilter."""
# -----------------------------------------------------------------------------# Imports# -----------------------------------------------------------------------------
import reimport sysimport warnings
from IPython.core.oinspect import OInfo
# -----------------------------------------------------------------------------# Main function# -----------------------------------------------------------------------------
# RegExp for splitting line contents into pre-char//first word-method//rest.# For clarity, each group in on one line.
# WARNING: update the regexp if the escapes in interactiveshell are changed, as# they are hardwired in.
# Although it's not solely driven by the regex, note that:# ,;/% only trigger if they are the first character on the line# ! and !! trigger if they are first char(s) *or* follow an indent# ? triggers as first or last char.
line_split = re.compile( r""" ^(\s*) # any leading space ([,;/%]|!!?|\?\??)? # escape character or characters \s*(%{0,2}[\w\.\*]*) # function/method, possibly with leading % # to correctly treat things like '?%magic' (.*?$|$) # rest of line """, re.VERBOSE,)
def split_user_input( line: str, pattern: re.Pattern[str] | None = None) -> tuple[str, str, str, str]: """Split user input into initial whitespace, escape character, function part and the rest. """ assert isinstance(line, str)
if pattern is None: pattern = line_split match = pattern.match(line) if not match: # print("match failed for line '%s'" % line) try: ifun, the_rest = line.split(None, 1) except ValueError: # print("split failed for line '%s'" % line) ifun, the_rest = line, "" pre = re.match(r"^(\s*)(.*)", line).groups()[0] esc = "" else: pre, esc, ifun, the_rest = match.groups()
# print('line:<%s>' % line) # dbg # print('pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest)) # dbg return pre, esc or "", ifun.strip(), the_rest
class LineInfo: """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.
raw_the_rest the_rest without whitespace stripped. """
line: str continue_prompt: bool pre: str esc: str ifun: str raw_the_rest: str the_rest: str pre_char: str pre_whitespace: str
def __init__(self, line: str, continue_prompt: bool = False) -> None: assert isinstance(line, str) self.line = line self.continue_prompt = continue_prompt self.pre, self.esc, self.ifun, self.raw_the_rest = split_user_input(line) self.the_rest = self.raw_the_rest.lstrip()
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.
.. deprecated:: 9.8 Use ``shell._ofind(line_info.ifun)`` directly instead. """ warnings.warn( "LineInfo.ofind() is deprecated since IPython 9.9. " "Use shell._ofind(line_info.ifun) directly instead.", DeprecationWarning, stacklevel=2, ) return ip._ofind(self.ifun)
def __str__(self) -> str: return "LineInfo [%s|%s|%s|%s]" % (self.pre, self.esc, self.ifun, self.the_rest)
def __repr__(self) -> str: return "<" + str(self) + ">"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128from datetime import datetimeimport osfrom random import choicefrom typing import Any
_tips: Any = { # (month, day) "every_year": { (1, 1): "Happy new year!", # European time: # [2/8/25, 23:28:24] Fernando Perez: Hi! Yes, this was my first public # announcement: # [2/8/25, 23:28:25] Fernando Perez: # https://mail.python.org/pipermail/python-list/2001-December/093408.html # [2/8/25, 23:28:55] Fernando Perez: All that started two months earlier # - in October 2001 I read this article: # [2/8/25, 23:28:55] Fernando Perez: # https://web.archive.org/web/20011202000624/http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html # [2/8/25, 23:29:05] Fernando Perez: Which is also archived here: # [2/8/25, 23:29:05] Fernando Perez: # https://docstore.mik.ua/orelly/weblinux2/orn/interactive_python.html # [2/8/25, 23:29:48] Fernando Perez: That article put me on the trail of # LazyPython, and I also found out (can’t remember where) about IPP # (Interactive Python Prompt), another similar projecd by Janko Hauser. # [2/8/25, 23:30:20] Fernando Perez: A also read an article around that # time, about new features in Python 2.0, which spoke of how # sys.displayhook could be programmed to call any object you wanted. # [2/8/25, 23:31:01] Fernando Perez: Those things together gave me the # idea of implementing a stateful object, the “IPython Prompt”, that # could store a cache of old results, Mathematica-style, and that could # have all kinds of other useful tricks up its sleeve. # [2/8/25, 23:31:17] Fernando Perez: I can’t remember if I did the # prompt stuff first and then read about LazyPython/IPP. # [2/8/25, 23:31:41] Fernando Perez: I do know that, implementation # wise, at first I just did the tiny IPython 0.0.1 that I posted much # later on github as a gist: # [2/8/25, 23:31:55] Fernando Perez: # https://gist.github.com/fperez/1579699 # [2/8/25, 23:32:03] Fernando Perez: But I only shared that publicly # much later. # [2/8/25, 23:33:19] Fernando Perez: I did find out about IPP/LazyPython # sometime in October, contacted Janko and Nathan who told me to use # their code at will but said they were busy with other things, and got # cranking for a few mad weeks on what became the IPython 0.2.0 that I # posted about in that comp.lang.python thread of December 2001. # [2/8/25, 23:33:52] Fernando Perez: That period from Oct 11 to Dec 9 # 2001 was maniacal coding, with very little sleep 🙂 ( 10, 11, ): "IPython's first line of code was written {} years ago by Fernando Pérez".format( datetime.now().year - 2001 ), ( 12, 9, ): "IPython 0.0.2 was announced {} years ago: https://mail.python.org/pipermail/python-list/2001-December/093408.html".format( datetime.now().year - 2001 ), ( 3, 8, ): "Today is International Women's Day: https://www.internationalwomensday.com/", ( 3, 31, ): "Happy International Transgender Day of Visibility! You are valid. You matter. https://en.wikipedia.org/wiki/International_Transgender_Day_of_Visibility", }, "random": [ "Use `F2` or %edit with no arguments to open an empty editor with a temporary file.", "Run your doctests from within IPython for development and debugging. The special %doctest_mode command toggles a mode where the prompt, output and exceptions display matches as closely as possible that of the default Python interpreter.", "You can use `files = !ls *.png`", "Use the IPython.lib.demo.Demo class to load any Python script as an interactive demo.", "Put a ';' at the end of a line to suppress the printing of output.", "You can use Ctrl-O to force a new line in terminal IPython", "Use `object?` to see the help on `object`, `object??` to view its source", "`?` alone on a line will brings up IPython's help", "You can use `%hist` to view history, see the options with `%history?`", "You can change the editing mode of IPython to behave more like vi, or emacs.", "IPython 9.0+ has hooks to integrate AI/LLM completions.", "Use `%timeit` or `%%timeit`, and the `-r`, `-n`, and `-o` options to easily profile your code.", "Use `ipython --help-all | less` to view all the IPython configuration options.", "Use `--theme`, or the `%colors` magic to change IPython's themes and colors.", "The `%timeit` magic has a `-o` flag, which returns the results, making it easy to plot. See `%timeit?`.", ],}
if os.name == "nt": _tips["random"].extend( [ "We can't show you all tips on Windows as sometimes Unicode characters crash the Windows console, please help us debug it." ] ) # unicode may crash windows console, so we filter out tips with non-ASCII characters. _tips["every_year"] = { k: v for k, v in _tips["every_year"].items() if all(ord(char) < 128 for char in v) }else: _tips["random"].extend( [ "You can use LaTeX or Unicode completion, `\\alpha<tab>` will insert the α symbol.", "You can find how to type a LaTeX symbol by back-completing it, eg `\\θ<tab>` will expand to `\\theta`.", "You can find how to type a Unicode symbol by back-completing it, eg `\\Ⅷ<tab>` will expand to `\\ROMAN NUMERAL EIGHT`.", "IPython supports combining unicode identifiers, eg F\\vec<tab> will become F⃗, useful for physics equations. Play with \\dot \\ddot and others.", ] )
# Check if argcomplete is installed and add tiptry: import argcomplete
_tips["random"].append( "Run `activate-global-python-argcomplete` from your shell to enable CLI completion for IPython" )except ModuleNotFoundError: pass
def pick_tip() -> str: current_date = datetime.now() month, day = current_date.month, current_date.day
if (month, day) in _tips["every_year"]: return _tips["every_year"][(month, day)]
return choice(_tips["random"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263"""Verbose and colourful traceback formatting.
**ColorTB**
I've always found it a bit hard to visually parse tracebacks in Python. TheColorTB class is a solution to that problem. It colors the different parts of atraceback in a manner similar to what you would expect from a syntax-highlightingtext editor.
Installation instructions for ColorTB::
import sys,ultratb sys.excepthook = ultratb.ColorTB()
**VerboseTB**
I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kindsof useful info when a traceback occurs. Ping originally had it spit out HTMLand intended it for CGI programmers, but why should they have all the fun? Ialtered it to spit out colored text to the terminal. It's a bit overwhelming,but kind of neat, and maybe useful for long-running programs that you believeare bug-free. If a crash *does* occur in that type of program you want details.Give it a shot--you'll love it or you'll hate it.
.. note::
The Verbose mode prints the variables currently visible where the exception happened (shortening their strings if too long). This can potentially be very slow, if you happen to have a huge data structure whose string representation is complex to compute. Your computer may appear to freeze for a while with cpu usage at 100%. If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting it more than once).
If you encounter this kind of situation often, you may want to use the Verbose_novars mode instead of the regular Verbose, which avoids formatting variables (but otherwise includes the information and context given by Verbose).
.. note::
The verbose mode print all variables in the stack, which means it can potentially leak sensitive information like access keys, or unencrypted password.
Installation instructions for VerboseTB::
import sys,ultratb sys.excepthook = ultratb.VerboseTB()
Note: Much of the code in this module was lifted verbatim from the standardlibrary module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
Inheritance diagram:
.. inheritance-diagram:: IPython.core.ultratb :parts: 3"""
# *****************************************************************************# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu># Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.# *****************************************************************************
import functoolsimport inspectimport linecacheimport sysimport timeimport tracebackimport typesimport warningsfrom collections.abc import Sequencefrom types import TracebackTypefrom typing import Any, List, Optional, Tuplefrom collections.abc import Callable
import stack_datafrom pygments.formatters.terminal256 import Terminal256Formatterfrom pygments.token import Token
from IPython import get_ipythonfrom IPython.utils import path as util_pathfrom IPython.utils import py3compatfrom IPython.utils.PyColorize import Parser, Theme, TokenStream, theme_tablefrom IPython.utils.terminal import get_terminal_size
from .display_trap import DisplayTrapfrom .doctb import DocTBfrom .tbtools import ( FrameInfo, TBTools, _format_traceback_lines, _safe_string, _simple_format_traceback_lines, _tokens_filename, eqrepr, get_line_number_of_frame, nullrepr, text_repr,)
# Globals# amount of space to put line numbers before verbose tracebacksINDENT_SIZE = 8
# When files are too long do not use stackdata to get frames.# it is too long.FAST_THRESHOLD = 10_000
# ---------------------------------------------------------------------------class ListTB(TBTools): """Print traceback information from a traceback list, with optional color.
Calling requires 3 arguments: (etype, evalue, elist) as would be obtained by::
etype, evalue, tb = sys.exc_info() if tb: elist = traceback.extract_tb(tb) else: elist = None
It can thus be used by programs which need to process the traceback before printing (such as console replacements based on the code module from the standard library).
Because they are meant to be called without a full traceback (only a list), instances of this class can't call the interactive pdb debugger."""
def __call__( self, etype: type[BaseException], evalue: BaseException | None, etb: TracebackType | None, ) -> None: self.ostream.flush() self.ostream.write(self.text(etype, evalue, etb)) self.ostream.write("\n")
def _extract_tb(self, tb: TracebackType | None) -> traceback.StackSummary | None: if tb: return traceback.extract_tb(tb) else: return None
def structured_traceback( self, etype: type, evalue: Optional[BaseException], etb: Optional[TracebackType] = None, tb_offset: Optional[int] = None, context: int = 5, ) -> list[str]: """Return a color formatted string with the traceback info.
Parameters ---------- etype : exception type Type of the exception raised. evalue : object Data stored in the exception etb : list | TracebackType | None If list: List of frames, see class docstring for details. If Traceback: Traceback of the exception. tb_offset : int, optional Number of frames in the traceback to skip. If not given, the instance evalue is used (set in constructor). context : int, optional Number of lines of context information to print.
Returns ------- String with formatted exception. """ # This is a workaround to get chained_exc_ids in recursive calls # etb should not be a tuple if structured_traceback is not recursive if isinstance(etb, tuple): etb, chained_exc_ids = etb else: chained_exc_ids = set() elist: list[Any] if isinstance(etb, list): elist = etb elif etb is not None: elist = self._extract_tb(etb) # type: ignore[assignment] else: elist = [] tb_offset = self.tb_offset if tb_offset is None else tb_offset assert isinstance(tb_offset, int) out_list: list[str] = [] if elist: if tb_offset and len(elist) > tb_offset: elist = elist[tb_offset:]
out_list.append( theme_table[self._theme_name].format( [ (Token, "Traceback"), (Token, " "), (Token.NormalEm, "(most recent call last)"), (Token, ":"), (Token, "\n"), ] ), ) out_list.extend(self._format_list(elist)) # The exception info should be a single entry in the list. lines = "".join(self._format_exception_only(etype, evalue)) out_list.append(lines)
# Find chained exceptions if we have a traceback (not for exception-only mode) if etb is not None: exception = self.get_parts_of_chained_exception(evalue)
if exception and (id(exception[1]) not in chained_exc_ids): chained_exception_message: list[str] = ( self.prepare_chained_exception_message(evalue.__cause__)[0] if evalue is not None else [""] ) etype, evalue, etb = exception # Trace exception to avoid infinite 'cause' loop chained_exc_ids.add(id(exception[1])) chained_exceptions_tb_offset = 0 ol1 = self.structured_traceback( etype, evalue, (etb, chained_exc_ids), # type: ignore[arg-type] chained_exceptions_tb_offset, context, ) ol2 = chained_exception_message
out_list = ol1 + ol2 + out_list
return out_list
def _format_list(self, extracted_list: list[Any]) -> list[str]: """Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.
Lifted almost verbatim from traceback.py """
output_list = [] for ind, (filename, lineno, name, line) in enumerate(extracted_list): # Will emphasize the last entry em = True if ind == len(extracted_list) - 1 else False
item = theme_table[self._theme_name].format( [(Token.NormalEm if em else Token.Normal, " ")] + _tokens_filename(em, filename, lineno=lineno) )
# This seem to be only in xmode plain (%run sinpleer), investigate why not share with verbose. # look at _tokens_filename in forma_record. if name != "<module>": item += theme_table[self._theme_name].format( [ (Token.NormalEm if em else Token.Normal, " in "), (Token.TB.NameEm if em else Token.TB.Name, name), ] ) item += theme_table[self._theme_name].format( [(Token.NormalEm if em else Token, "\n")] ) if line: item += theme_table[self._theme_name].format( [ (Token.Line if em else Token, " "), (Token.Line if em else Token, line.strip()), (Token, "\n"), ] ) output_list.append(item)
return output_list
def _format_exception_only( self, etype: type[BaseException], value: BaseException | None ) -> list[str]: """Format the exception part of a traceback.
The arguments are the exception type and value such as given by sys.exc_info()[:2]. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.
Also lifted nearly verbatim from traceback.py """ have_filedata = False output_list = [] stype_tokens = [(Token.ExcName, etype.__name__)] stype: str = theme_table[self._theme_name].format(stype_tokens) if value is None: # Not sure if this can still happen in Python 2.6 and above output_list.append(stype + "\n") else: if issubclass(etype, SyntaxError): assert hasattr(value, "filename") assert hasattr(value, "lineno") assert hasattr(value, "text") assert hasattr(value, "offset") assert hasattr(value, "msg") have_filedata = True if not value.filename: value.filename = "<string>" if value.lineno: lineno = value.lineno textline = linecache.getline(value.filename, value.lineno) else: lineno = "unknown" textline = "" output_list.append( theme_table[self._theme_name].format( [(Token, " ")] + _tokens_filename( True, value.filename, lineno=(None if lineno == "unknown" else lineno), ) + [(Token, "\n")] ) ) if textline == "": # sep 2025: # textline = py3compat.cast_unicode(value.text, "utf-8") if value.text is None: textline = "" else: assert isinstance(value.text, str) textline = value.text
if textline is not None: i = 0 while i < len(textline) and textline[i].isspace(): i += 1 output_list.append( theme_table[self._theme_name].format( [ (Token.Line, " "), (Token.Line, textline.strip()), (Token, "\n"), ] ) ) if value.offset is not None: s = " " for c in textline[i : value.offset - 1]: if c.isspace(): s += c else: s += " " output_list.append( theme_table[self._theme_name].format( [(Token.Caret, s + "^"), (Token, "\n")] ) ) s = value.msg else: s = self._some_str(value) if s: output_list.append( theme_table[self._theme_name].format( stype_tokens + [ (Token.ExcName, ":"), (Token, " "), (Token, s), (Token, "\n"), ] ) ) else: output_list.append("%s\n" % stype)
# PEP-678 notes output_list.extend(f"{x}\n" for x in getattr(value, "__notes__", []))
# sync with user hooks if have_filedata: ipinst = get_ipython() if ipinst is not None: assert value is not None assert hasattr(value, "lineno") assert hasattr(value, "filename") ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
return output_list
def get_exception_only(self, etype, value): """Only print the exception type and message, without a traceback.
Parameters ---------- etype : exception type value : exception value """ return ListTB.structured_traceback(self, etype, value)
def show_exception_only( self, etype: BaseException | None, evalue: TracebackType | None ) -> None: """Only print the exception type and message, without a traceback.
Parameters ---------- etype : exception type evalue : exception value """ # This method needs to use __call__ from *this* class, not the one from # a subclass whose signature or behavior may be different ostream = self.ostream ostream.flush() ostream.write("\n".join(self.get_exception_only(etype, evalue))) ostream.flush()
def _some_str(self, value: Any) -> str: # Lifted from traceback.py try: return str(value) except: return "<unprintable %s object>" % type(value).__name__
_sentinel = object()_default = "default"
# ----------------------------------------------------------------------------class VerboseTB(TBTools): """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead of HTML. Requires inspect and pydoc. Crazy, man.
Modified version which optionally strips the topmost entries from the traceback, to be used with alternate interpreters (because their own code would appear in the traceback)."""
tb_highlight = "bg:ansiyellow" tb_highlight_style = "default"
_mode: str
def __init__( self, # TODO: no default ? theme_name: str = _default, call_pdb: bool = False, ostream: Any = None, tb_offset: int = 0, long_header: bool = False, include_vars: bool = True, check_cache: Callable[[], None] | None = None, debugger_cls: type | None = None, *, color_scheme: Any = _sentinel, ): """Specify traceback offset, headers and color scheme.
Define how many frames to drop from the tracebacks. Calling it with tb_offset=1 allows use of this handler in interpreters which will have their own code at the top of the traceback (VerboseTB will first remove that frame before printing the traceback info).""" if color_scheme is not _sentinel: assert isinstance(color_scheme, str) theme_name = color_scheme.lower()
warnings.warn( "color_scheme is deprecated as of IPython 9.0 and replaced by " "theme_name (which should be lowercase). As you passed a " "color_scheme value I will try to see if I have corresponding " "theme.", stacklevel=2, category=DeprecationWarning, )
if theme_name != _default: warnings.warn( "You passed both `theme_name` and `color_scheme` " "(deprecated) to VerboseTB constructor. `theme_name` will " "be ignored for the time being.", stacklevel=2, category=DeprecationWarning, )
if theme_name == _default: theme_name = "linux"
assert isinstance(theme_name, str) super().__init__( theme_name=theme_name, call_pdb=call_pdb, ostream=ostream, debugger_cls=debugger_cls, ) self.tb_offset = tb_offset self.long_header = long_header self.include_vars = include_vars # By default we use linecache.checkcache, but the user can provide a # different check_cache implementation. This was formerly used by the # IPython kernel for interactive code, but is no longer necessary. if check_cache is None: check_cache = linecache.checkcache self.check_cache = check_cache
self.skip_hidden = True
def format_record(self, frame_info: FrameInfo) -> str: """Format a single stack frame""" assert isinstance(frame_info, FrameInfo)
if isinstance(frame_info._sd, stack_data.RepeatedFrames): return theme_table[self._theme_name].format( [ (Token, " "), ( Token.ExcName, "[... skipping similar frames: %s]" % frame_info.description, ), (Token, "\n"), ] )
indent: str = " " * INDENT_SIZE
assert isinstance(frame_info.lineno, int) args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame) if frame_info.executing is not None: func = frame_info.executing.code_qualname() else: func = "?" if func == "<module>": call = "" else: # Decide whether to include variable details or not var_repr = eqrepr if self.include_vars else nullrepr try: scope = inspect.formatargvalues( args, varargs, varkw, locals_, formatvalue=var_repr ) assert isinstance(scope, str) call = theme_table[self._theme_name].format( [(Token, "in "), (Token.VName, func), (Token.ValEm, scope)] ) except KeyError: # This happens in situations like errors inside generator # expressions, where local variables are listed in the # line, but can't be extracted from the frame. I'm not # 100% sure this isn't actually a bug in inspect itself, # but since there's no info for us to compute with, the # best we can do is report the failure and move on. Here # we must *not* call any traceback construction again, # because that would mess up use of %debug later on. So we # simply report the failure and move on. The only # limitation will be that this frame won't have locals # listed in the call signature. Quite subtle problem... # I can't think of a good way to validate this in a unit # test, but running a script consisting of: # dict( (k,v.strip()) for (k,v) in range(10) ) # will illustrate the error, if this exception catch is # disabled. call = theme_table[self._theme_name].format( [ (Token, "in "), (Token.VName, func), (Token.ValEm, "(***failed resolving arguments***)"), ] )
lvals_toks: list[TokenStream] = [] if self.include_vars: try: # we likely want to fix stackdata at some point, but # still need a workaround. fibp = frame_info.variables_in_executing_piece for var in fibp: lvals_toks.append( [ (Token, var.name), (Token, " "), (Token.ValEm, "= "), (Token.ValEm, repr(var.value)), ] ) except Exception: lvals_toks.append( [ ( Token, "Exception trying to inspect frame. No more locals available.", ), ] )
if frame_info._sd is None: # fast fallback if file is too long assert frame_info.filename is not None level_tokens = [ (Token.FilenameEm, util_path.compress_user(frame_info.filename)), (Token, " "), (Token, call), (Token, "\n"), ]
_line_format = Parser(theme_name=self._theme_name).format2 assert isinstance(frame_info.code, types.CodeType) first_line: int = frame_info.code.co_firstlineno current_line: int = frame_info.lineno raw_lines: list[str] = frame_info.raw_lines index: int = current_line - first_line assert frame_info.context is not None if index >= frame_info.context: start = max(index - frame_info.context, 0) stop = index + frame_info.context index = frame_info.context else: start = 0 stop = index + frame_info.context raw_lines = raw_lines[start:stop]
# Jan 2025: may need _line_format(py3ompat.cast_unicode(s)) raw_color_err = [] for s in raw_lines: formatted, is_error = _line_format(s, "str") assert formatted is not None, "format2 should return str when out='str'" raw_color_err.append((s, (formatted, is_error)))
tb_tokens = _simple_format_traceback_lines( current_line, index, raw_color_err, lvals_toks, theme=theme_table[self._theme_name], ) _tb_lines: str = theme_table[self._theme_name].format(tb_tokens)
return theme_table[self._theme_name].format(level_tokens + tb_tokens) else: result = theme_table[self._theme_name].format( _tokens_filename(True, frame_info.filename, lineno=frame_info.lineno) ) result += ", " if call else "" result += f"{call}\n" result += theme_table[self._theme_name].format( _format_traceback_lines( frame_info.lines, theme_table[self._theme_name], self.has_colors, lvals_toks, ) ) return result
def prepare_header(self, etype: str, long_version: bool = False) -> str: width = min(75, get_terminal_size()[0]) if long_version: # Header with the exception type, python version, and date pyver = "Python " + sys.version.split()[0] + ": " + sys.executable date = time.ctime(time.time()) theme = theme_table[self._theme_name] head = theme.format( [ (Token.Topline, theme.symbols["top_line"] * width), (Token, "\n"), (Token.ExcName, etype), (Token, " " * (width - len(etype) - len(pyver))), (Token, pyver), (Token, "\n"), (Token, date.rjust(width)), ] ) head += ( "\nA problem occurred executing Python code. Here is the sequence of function" "\ncalls leading up to the error, with the most recent (innermost) call last." ) else: # Simplified header head = theme_table[self._theme_name].format( [ (Token.ExcName, etype), ( Token, "Traceback (most recent call last)".rjust(width - len(etype)), ), ] )
return head
def format_exception(self, etype, evalue): # Get (safely) a string form of the exception info try: etype_str, evalue_str = map(str, (etype, evalue)) except: # User exception is improperly defined. etype, evalue = str, sys.exc_info()[:2] etype_str, evalue_str = map(str, (etype, evalue))
# PEP-678 notes notes = getattr(evalue, "__notes__", []) if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)): notes = [_safe_string(notes, "__notes__", func=repr)]
for note in notes: assert isinstance(note, str)
str_notes: Sequence[str] = notes
# ... and format it return [ theme_table[self._theme_name].format( [(Token.ExcName, etype_str), (Token, ": "), (Token, evalue_str)] ), *( theme_table[self._theme_name].format([(Token, note)]) for note in str_notes ), ]
def format_exception_as_a_whole( self, etype: type, evalue: Optional[BaseException], etb: Optional[TracebackType], context: int, tb_offset: Optional[int], ) -> list[list[str]]: """Formats the header, traceback and exception message for a single exception.
This may be called multiple times by Python 3 exception chaining (PEP 3134). """ # some locals orig_etype = etype try: etype = etype.__name__ # type: ignore[assignment] except AttributeError: pass
tb_offset = self.tb_offset if tb_offset is None else tb_offset assert isinstance(tb_offset, int) head = self.prepare_header(str(etype), self.long_header) records = self.get_records(etb, context, tb_offset) if etb else []
frames = [] skipped = 0 lastrecord = len(records) - 1 for i, record in enumerate(records): if ( not isinstance(record._sd, stack_data.RepeatedFrames) and self.skip_hidden ): if ( record.frame.f_locals.get("__tracebackhide__", 0) and i != lastrecord ): skipped += 1 continue if skipped: frames.append( theme_table[self._theme_name].format( [ (Token, " "), (Token.ExcName, "[... skipping hidden %s frame]" % skipped), (Token, "\n"), ] ) ) skipped = 0 frames.append(self.format_record(record)) if skipped: frames.append( theme_table[self._theme_name].format( [ (Token, " "), (Token.ExcName, "[... skipping hidden %s frame]" % skipped), (Token, "\n"), ] ) )
formatted_exception = self.format_exception(etype, evalue) if records: frame_info = records[-1] ipinst = get_ipython() if ipinst is not None: ipinst.hooks.synchronize_with_editor( frame_info.filename, frame_info.lineno, 0 )
return [[head] + frames + formatted_exception]
def get_records(self, etb: TracebackType, context: int, tb_offset: int) -> Any: assert etb is not None context = context - 1 after = context // 2 before = context - after if self.has_colors: base_style = theme_table[self._theme_name].as_pygments_style() style = stack_data.style_with_executing_node(base_style, self.tb_highlight) formatter = Terminal256Formatter(style=style) else: formatter = None options = stack_data.Options( before=before, after=after, pygments_formatter=formatter, )
# Let's estimate the amount of code we will have to parse/highlight. cf: Optional[TracebackType] = etb max_len = 0 tbs = [] while cf is not None: try: mod = inspect.getmodule(cf.tb_frame) if mod is not None: mod_name = mod.__name__ root_name, *_ = mod_name.split(".") if root_name == "IPython": cf = cf.tb_next continue max_len = get_line_number_of_frame(cf.tb_frame)
except OSError: max_len = 0 max_len = max(max_len, max_len) tbs.append(cf) cf = getattr(cf, "tb_next", None)
if max_len > FAST_THRESHOLD: FIs: list[FrameInfo] = [] for tb in tbs: frame = tb.tb_frame # type: ignore[union-attr] lineno = frame.f_lineno code = frame.f_code filename = code.co_filename # TODO: Here we need to use before/after/ FIs.append( FrameInfo( "Raw frame", filename, lineno, frame, code, context=context ) ) return FIs res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:] res2 = [FrameInfo._from_stack_data_FrameInfo(r) for r in res] return res2
def structured_traceback( self, etype: type, evalue: Optional[BaseException], etb: Optional[TracebackType] = None, tb_offset: Optional[int] = None, context: int = 5, ) -> list[str]: """Return a nice text document describing the traceback.""" formatted_exceptions: list[list[str]] = self.format_exception_as_a_whole( etype, evalue, etb, context, tb_offset )
termsize = min(75, get_terminal_size()[0]) theme = theme_table[self._theme_name] head: str = theme.format( [ ( Token.Topline, theme.symbols["top_line"] * termsize, ), ] ) structured_traceback_parts: list[str] = [head] chained_exceptions_tb_offset = 0 lines_of_context = 3 exception = self.get_parts_of_chained_exception(evalue) if exception: assert evalue is not None formatted_exceptions += self.prepare_chained_exception_message( evalue.__cause__ ) etype, evalue, etb = exception else: evalue = None chained_exc_ids = set() while evalue: formatted_exceptions += self.format_exception_as_a_whole( etype, evalue, etb, lines_of_context, chained_exceptions_tb_offset ) exception = self.get_parts_of_chained_exception(evalue)
if exception and id(exception[1]) not in chained_exc_ids: chained_exc_ids.add( id(exception[1]) ) # trace exception to avoid infinite 'cause' loop formatted_exceptions += self.prepare_chained_exception_message( evalue.__cause__ ) etype, evalue, etb = exception else: evalue = None
# we want to see exceptions in a reversed order: # the first exception should be on top for fx in reversed(formatted_exceptions): structured_traceback_parts += fx
return structured_traceback_parts
def debugger(self, force: bool = False) -> None: """Call up the pdb debugger if desired, always clean up the tb reference.
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 the call_pdb flag is set, the pdb interactive debugger is invoked. In all cases, the self.tb reference to the current traceback is deleted to prevent lingering references which hamper memory management.
Note that each call to pdb() does an 'import readline', so if your app requires a special setup for the readline completers, you'll have to fix that by hand after invoking the exception handler."""
if force or self.call_pdb: if self.pdb is None: self.pdb = self.debugger_cls() # the system displayhook may have changed, restore the original # for pdb display_trap = DisplayTrap(hook=sys.__displayhook__) with display_trap: self.pdb.reset() # Find the right frame so we don't pop up inside ipython itself if hasattr(self, "tb") and self.tb is not None: # type: ignore[has-type] etb = self.tb # type: ignore[has-type] else: etb = self.tb = sys.last_traceback while self.tb is not None and self.tb.tb_next is not None: assert self.tb.tb_next is not None self.tb = self.tb.tb_next if etb and etb.tb_next: etb = etb.tb_next self.pdb.botframe = etb.tb_frame # last_value should be deprecated, but last-exc sometimme not set # please check why later and remove the getattr. exc = ( sys.last_value if sys.version_info < (3, 12) else getattr(sys, "last_exc", sys.last_value) ) # type: ignore[attr-defined] if exc: self.pdb.interaction(None, exc) else: self.pdb.interaction(None, etb)
if hasattr(self, "tb"): del self.tb
def handler(self, info=None): (etype, evalue, etb) = info or sys.exc_info() self.tb = etb ostream = self.ostream ostream.flush() ostream.write(self.text(etype, evalue, etb)) # type:ignore[arg-type] ostream.write("\n") ostream.flush()
# Changed so an instance can just be called as VerboseTB_inst() and print # out the right info on its own. def __call__(self, etype=None, evalue=None, etb=None): """This hook can replace sys.excepthook (for Python 2.1 or higher).""" if etb is None: self.handler() else: self.handler((etype, evalue, etb)) try: self.debugger() except KeyboardInterrupt: print("\nKeyboardInterrupt")
# ----------------------------------------------------------------------------class FormattedTB(VerboseTB, ListTB): """Subclass ListTB but allow calling with a traceback.
It can thus be used as a sys.excepthook for Python > 2.1.
Also adds 'Context' and 'Verbose' modes, not available in ListTB.
Allows a tb_offset to be specified. This is useful for situations where one needs to remove a number of topmost frames from the traceback (such as occurs with python programs that themselves execute other python code, like Python shells)."""
mode: str
def __init__( self, mode="Plain", # TODO: no default theme_name="linux", call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=False, check_cache=None, debugger_cls=None, ): # NEVER change the order of this list. Put new modes at the end: self.valid_modes = ["Plain", "Context", "Verbose", "Minimal", "Docs"] self.verbose_modes = self.valid_modes[1:3]
VerboseTB.__init__( self, theme_name=theme_name, call_pdb=call_pdb, ostream=ostream, tb_offset=tb_offset, long_header=long_header, include_vars=include_vars, check_cache=check_cache, debugger_cls=debugger_cls, )
# Different types of tracebacks are joined with different separators to # form a single string. They are taken from this dict self._join_chars = dict( Plain="", Context="\n", Verbose="\n", Minimal="", Docs="" ) # set_mode also sets the tb_join_char attribute self.set_mode(mode)
def structured_traceback( self, etype: type, evalue: BaseException | None, etb: TracebackType | None = None, tb_offset: int | None = None, context: int = 5, ) -> list[str]: tb_offset = self.tb_offset if tb_offset is None else tb_offset mode = self.mode if mode in self.verbose_modes: # Verbose modes need a full traceback return VerboseTB.structured_traceback( self, etype, evalue, etb, tb_offset, context ) elif mode == "Docs": # return DocTB return DocTB( theme_name=self._theme_name, call_pdb=self.call_pdb, ostream=self.ostream, tb_offset=tb_offset, long_header=self.long_header, include_vars=self.include_vars, check_cache=self.check_cache, debugger_cls=self.debugger_cls, ).structured_traceback( etype, evalue, etb, tb_offset, 1 ) # type: ignore[arg-type]
elif mode == "Minimal": return ListTB.get_exception_only(self, etype, evalue) else: # We must check the source cache because otherwise we can print # out-of-date source code. self.check_cache() # Now we can extract and format the exception return ListTB.structured_traceback( self, etype, evalue, etb, tb_offset, context )
def stb2text(self, stb: list[str]) -> str: """Convert a structured traceback (a list) to a string.""" return self.tb_join_char.join(stb)
def set_mode(self, mode: Optional[str] = None) -> None: """Switch to the desired mode.
If mode is not specified, cycles through the available modes."""
if not mode: new_idx = (self.valid_modes.index(self.mode) + 1) % len(self.valid_modes) self.mode = self.valid_modes[new_idx] elif mode not in self.valid_modes: raise ValueError( "Unrecognized mode in FormattedTB: <" + mode + ">\n" "Valid modes: " + str(self.valid_modes) ) else: assert isinstance(mode, str) self.mode = mode # include variable details only in 'Verbose' mode self.include_vars = self.mode == self.valid_modes[2] # Set the join character for generating text tracebacks self.tb_join_char = self._join_chars[self.mode]
# some convenient shortcuts def plain(self) -> None: self.set_mode(self.valid_modes[0])
def context(self) -> None: self.set_mode(self.valid_modes[1])
def verbose(self) -> None: self.set_mode(self.valid_modes[2])
def minimal(self) -> None: self.set_mode(self.valid_modes[3])
# ----------------------------------------------------------------------------class AutoFormattedTB(FormattedTB): """A traceback printer which can be called on the fly.
It will find out about exceptions by itself.
A brief example::
AutoTB = AutoFormattedTB(mode = 'Verbose', theme_name='linux') try: ... except: AutoTB() # or AutoTB(out=logfile) where logfile is an open file object """
def __call__( self, etype: type | None = None, evalue: BaseException | None = None, etb: TracebackType | None = None, out: Any = None, tb_offset: int | None = None, ) -> None: """Print out a formatted exception traceback.
Optional arguments: - out: an open file-like object to direct output to.
- tb_offset: the number of frames to skip over in the stack, on a per-call basis (this overrides temporarily the instance's tb_offset given at initialization time."""
if out is None: out = self.ostream out.flush() out.write(self.text(etype, evalue, etb, tb_offset)) # type:ignore[arg-type] out.write("\n") out.flush() # FIXME: we should remove the auto pdb behavior from here and leave # that to the clients. try: self.debugger() except KeyboardInterrupt: print("\nKeyboardInterrupt")
def structured_traceback( self, etype: type, evalue: Optional[BaseException], etb: Optional[TracebackType] = None, tb_offset: Optional[int] = None, context: int = 5, ) -> list[str]: # tb: TracebackType or tupleof tb types ? if etype is None: etype, evalue, etb = sys.exc_info() if isinstance(etb, tuple): # tb is a tuple if this is a chained exception. self.tb = etb[0] else: self.tb = etb return FormattedTB.structured_traceback( self, etype, evalue, etb, tb_offset, context )
# ---------------------------------------------------------------------------
# A simple class to preserve Nathan's original functionality.class ColorTB(FormattedTB): """Deprecated since IPython 9.0."""
def __init__(self, *args, **kwargs): warnings.warn( "Deprecated since IPython 9.0 use FormattedTB directly ColorTB is just an alias", DeprecationWarning, stacklevel=2, )
super().__init__(*args, **kwargs)
class SyntaxTB(ListTB): """Extension which holds some state: the last exception value"""
last_syntax_error: BaseException | None
def __init__(self, *, theme_name): super().__init__(theme_name=theme_name) self.last_syntax_error = None
def __call__(self, etype, value, elist): self.last_syntax_error = value
super().__call__(etype, value, elist)
def structured_traceback( self, etype: type, evalue: BaseException | None, etb: TracebackType | None = None, tb_offset: int | None = None, context: int = 5, ) -> list[str]: value = evalue # If the source file has been edited, the line in the syntax error can # be wrong (retrieved from an outdated cache). This replaces it with # the current value. if ( isinstance(value, SyntaxError) and isinstance(value.filename, str) and isinstance(value.lineno, int) ): linecache.checkcache(value.filename) newtext = linecache.getline(value.filename, value.lineno) if newtext: value.text = newtext self.last_syntax_error = value return super(SyntaxTB, self).structured_traceback( etype, value, etb, tb_offset=tb_offset, context=context )
def clear_err_state(self) -> Any | None: """Return the current error state and clear it""" e = self.last_syntax_error self.last_syntax_error = None return e
def stb2text(self, stb: list[str]) -> str: """Convert a structured traceback (a list) to a string.""" return "".join(stb)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341# -*- coding: utf-8 -*-"""Usage information for the main IPython applications."""#-----------------------------------------------------------------------------# Copyright (C) 2008-2011 The IPython Development Team# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#-----------------------------------------------------------------------------
import sysfrom IPython.core import release
cl_usage = """\========= IPython=========
Tools for Interactive Computing in Python=========================================
A Python shell with automatic history (input and output), dynamic object introspection, easier configuration, command completion, access to the system shell and more. IPython can also be embedded in running programs.
Usage
ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...
If invoked with no options, it executes the file and exits, passing the remaining arguments to the script, just as if you had specified the same command with python. You may need to specify `--` before args to be passed to the script, to prevent IPython from attempting to parse them. If you specify the option `-i` before the filename, it will enter an interactive IPython session after running the script, rather than exiting. Files ending in .py will be treated as normal Python, but files ending in .ipy can contain special IPython syntax (magic commands, shell expansions, etc.).
Almost all configuration in IPython is available via the command-line. Do `ipython --help-all` to see all available options. For persistent configuration, look into your `ipython_config.py` configuration file for details.
This file is typically installed in the `IPYTHONDIR` directory, and there is a separate configuration directory for each profile. The default profile directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to C:\\Users\\YourUserName in most instances.
To initialize a profile with the default configuration file, do::
$> ipython profile create
and start editing `IPYTHONDIR/profile_default/ipython_config.py`
In IPython's documentation, we will refer to this directory as `IPYTHONDIR`, you can change its default location by creating an environment variable with this name and setting it to the desired path.
For more information, see the manual available in HTML and PDF in your installation, or online at https://ipython.org/documentation.html."""
interactive_usage = """IPython -- An enhanced Interactive Python=========================================
IPython offers a fully compatible replacement for the standard Pythoninterpreter, with convenient shell features, special commands, commandhistory mechanism and output results caching.
At your system command line, type 'ipython -h' to see the command lineoptions available. This document only describes interactive features.
GETTING HELP------------
Within IPython you have various way to access help:
? -> Introduction and overview of IPython's features (this screen). object? -> Details about 'object'. object?? -> More detailed, verbose information about 'object'. %quickref -> Quick reference of all IPython specific syntax and magics. help -> Access Python's own help system.
If you are in terminal IPython you can quit this screen by pressing `q`.
MAIN FEATURES-------------
* Access to the standard Python help with object docstrings and the Python manuals. Simply type 'help' (no quotes) to invoke it.
* Magic commands: type %magic for information on the magic subsystem.
* System command aliases, via the %alias command or the configuration file(s).
* Dynamic object information:
Typing ?word or word? prints detailed information about an object. Certain long strings (code, etc.) get snipped in the center for brevity.
Typing ??word or word?? gives access to the full information without snipping long strings. Strings that are longer than the screen are printed through the less pager.
The ?/?? system gives access to the full source code for any object (if available), shows function prototypes and other useful information.
If you just want to see an object's docstring, type '%pdoc object' (without quotes, and without % if you have automagic on).
* Tab completion in the local namespace:
At any time, hitting tab will complete any available python commands or variable names, and show you a list of the possible completions if there's no unambiguous one. It will also complete filenames in the current directory.
* Search previous command history in multiple ways:
- Start typing, and then use arrow keys up/down or (Ctrl-p/Ctrl-n) to search through the history items that match what you've typed so far.
- Hit Ctrl-r: opens a search prompt. Begin typing and the system searches your history for lines that match what you've typed so far, completing as much as it can.
- %hist: search history by index.
* Persistent command history across sessions.
* Logging of input with the ability to save and restore a working session.
* System shell with !. Typing !ls will run 'ls' in the current directory.
* The reload command does a 'deep' reload of a module: changes made to the module since you imported will actually be available without having to exit.
* Verbose and colored exception traceback printouts. See the magic xmode and xcolor functions for details (just type %magic).
* Input caching system:
IPython offers numbered prompts (In/Out) with input and output caching. All input is saved and can be retrieved as variables (besides the usual arrow key recall).
The following GLOBAL variables always exist (so don't overwrite them!): _i: stores previous input. _ii: next previous. _iii: next-next previous. _ih : a list of all input _ih[n] is the input from line n.
Additionally, global variables named _i<n> are dynamically created (<n> being the prompt counter), such that _i<n> == _ih[<n>]
For example, what you typed at prompt 14 is available as _i14 and _ih[14].
You can create macros which contain multiple input lines from this history, for later re-execution, with the %macro function.
The history function %hist allows you to see any part of your input history by printing a range of the _i variables. Note that inputs which contain magic functions (%) appear in the history with a prepended comment. This is because they aren't really valid Python code, so you can't exec them.
* Output caching system:
For output that is returned from actions, a system similar to the input cache exists but using _ instead of _i. Only actions that produce a result (NOT assignments, for example) are cached. If you are familiar with Mathematica, IPython's _ variables behave exactly like Mathematica's % variables.
The following GLOBAL variables always exist (so don't overwrite them!): _ (one underscore): previous output. __ (two underscores): next previous. ___ (three underscores): next-next previous.
Global variables named _<n> are dynamically created (<n> being the prompt counter), such that the result of output <n> is always available as _<n>.
Finally, a global dictionary named _oh exists with entries for all lines which generated output.
* Directory history:
Your history of visited directories is kept in the global list _dh, and the magic %cd command can be used to go to any entry in that list.
* Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
1. Auto-parentheses Callable objects (i.e. functions, methods, etc) can be invoked like this (notice the commas between the arguments):: In [1]: callable_ob arg1, arg2, arg3 and the input will be translated to this:: callable_ob(arg1, arg2, arg3) This feature is off by default (in rare cases it can produce undesirable side-effects), but you can activate it at the command-line by starting IPython with `--autocall 1`, set it permanently in your configuration file, or turn on at runtime with `%autocall 1`.
You can force auto-parentheses by using '/' as the first character of a line. For example:: In [1]: /globals # becomes 'globals()' Note that the '/' MUST be the first character on the line! This won't work:: In [2]: print /globals # syntax error
In most cases the automatic algorithm should work, so you should rarely need to explicitly invoke /. One notable exception is if you are trying to call a function with a list of tuples as arguments (the parenthesis will confuse IPython):: In [1]: zip (1,2,3),(4,5,6) # won't work but this will work:: In [2]: /zip (1,2,3),(4,5,6) ------> zip ((1,2,3),(4,5,6)) Out[2]= [(1, 4), (2, 5), (3, 6)]
IPython tells you that it has altered your command line by displaying the new command line preceded by -->. e.g.:: In [18]: callable list -------> callable (list)
2. Auto-Quoting You can force auto-quoting of a function's arguments by using ',' as the first character of a line. For example:: In [1]: ,my_function /home/me # becomes my_function("/home/me")
If you use ';' instead, the whole argument is quoted as a single string (while ',' splits on whitespace):: In [2]: ,my_function a b c # becomes my_function("a","b","c") In [3]: ;my_function a b c # becomes my_function("a b c")
Note that the ',' MUST be the first character on the line! This won't work:: In [4]: x = ,my_function /home/me # syntax error"""
interactive_usage_min = """\An enhanced console for Python.Some of its features are:- Tab completion in the local namespace.- Logging of input, see command-line options.- System shell escape via ! , eg !ls.- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)- Keeps track of locally defined variables via %who, %whos.- Show object information with a ? eg ?x or x? (use ?? for more info)."""
quick_reference = r"""IPython -- An enhanced Interactive Python - Quick Reference Card================================================================
obj?, obj?? : Get help, or more help for object (also works as ?obj, ??obj).?foo.*abc* : List names in 'foo' containing 'abc' in them.%magic : Information about IPython's 'magic' % functions.
Magic functions are prefixed by % or %%, and typically take their argumentswithout parentheses, quotes or even commas for convenience. Line magics take asingle % and cell magics are prefixed with two %%.
Example magic function calls:
%alias d ls -F : 'd' is now an alias for 'ls -F'alias d ls -F : Works if 'alias' not a python namealist = %alias : Get list of aliases to 'alist'cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.%cd?? : See help AND source for magic %cd%timeit x=10 : time the 'x=10' statement with high precision.%%timeit x=2**100x**100 : time 'x**100' with a setup of 'x=2**100'; setup code is not counted. This is an example of a cell magic.
System commands:
!cp a.txt b/ : System command escape, calls os.system()cp a.txt b/ : after %rehashx, most system commands work without !cp ${f}.txt $bar : Variable expansion in magics and system commandsfiles = !ls /usr : Capture system command outputfiles.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
History:
_i, _ii, _iii : Previous, next previous, next next previous input_i4, _ih[2:5] : Input history line 4, lines 2-4exec(_i81) : Execute input history line #81 again%rep 81 : Edit input history line #81_, __, ___ : previous, next previous, next next previous output_dh : Directory history_oh : Output history%hist : Command history of current session.%hist -g foo : Search command history of (almost) all sessions for 'foo'.%hist -g : Command history of (almost) all sessions.%hist 1/2-8 : Command history containing lines 2-8 of session 1.%hist 1/ ~2/ : Command history of session 1 and 2 sessions before current.%hist ~8/1-~6/5 : Command history from line 1 of 8 sessions ago to line 5 of 6 sessions ago.%edit 0/ : Open editor to execute code with history of current session.
Autocall:
f 1,2 : f(1,2) # Off by default, enable with %autocall magic./f 1,2 : f(1,2) (forced autoparen),f 1 2 : f("1","2");f 1 2 : f("1 2")
Remember: TAB completion works in many contexts, not just file namesor python names.
The following magic functions are currently available:
"""
default_banner_parts = ["Python %s\n"%sys.version.split("\n")[0], "Type 'copyright', 'credits' or 'license' for more information\n" , "IPython {version} -- An enhanced Interactive Python. Type '?' for help.\n".format(version=release.version),]
default_banner = ''.join(default_banner_parts)1234567891011# encoding: utf-8"""Extra capabilities for IPython"""
# -----------------------------------------------------------------------------# Copyright (C) 2008-2011 The IPython Development Team## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.# -----------------------------------------------------------------------------123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491# -*- coding: utf-8 -*-"""Manage background (threaded) jobs conveniently from an interactive shell.
This module provides a BackgroundJobManager class. This is the main classmeant for public usage, it implements an object which can create and managenew background jobs.
It also provides the actual job classes managed by these BackgroundJobManagerobjects, see their docstrings below.
This system was inspired by discussions with B. Granger and theBackgroundCommand class described in the book Python Scripting forComputational Science, by H. P. Langtangen:
http://folk.uio.no/hpl/scripting
(although ultimately no code from this text was used, as IPython's system is aseparate implementation).
An example notebook is provided in our documentation illustrating interactiveuse of the system."""
#*****************************************************************************# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#*****************************************************************************
# Code beginsimport sysimport threading
from IPython import get_ipythonfrom IPython.core.ultratb import AutoFormattedTBfrom logging import error, debug
class BackgroundJobManager: """Class to manage a pool of backgrounded threaded jobs.
Below, we assume that 'jobs' is a BackgroundJobManager instance. Usage summary (see the method docstrings for details):
jobs.new(...) -> start a new job jobs() or jobs.status() -> print status summary of all jobs
jobs[N] -> returns job number N.
foo = jobs[N].result -> assign to variable foo the result of job N
jobs[N].traceback() -> print the traceback of dead job N
jobs.remove(N) -> remove (finished) job N
jobs.flush() -> remove all finished jobs As a convenience feature, BackgroundJobManager instances provide the utility result and traceback methods which retrieve the corresponding information from the jobs list:
jobs.result(N) <--> jobs[N].result jobs.traceback(N) <--> jobs[N].traceback()
While this appears minor, it allows you to use tab completion interactively on the job manager instance. """
def __init__(self): # Lists for job management, accessed via a property to ensure they're # up to date.x self._running = [] self._completed = [] self._dead = [] # A dict of all jobs, so users can easily access any of them self.all = {} # For reporting self._comp_report = [] self._dead_report = [] # Store status codes locally for fast lookups self._s_created = BackgroundJobBase.stat_created_c self._s_running = BackgroundJobBase.stat_running_c self._s_completed = BackgroundJobBase.stat_completed_c self._s_dead = BackgroundJobBase.stat_dead_c self._current_job_id = 0
@property def running(self): self._update_status() return self._running
@property def dead(self): self._update_status() return self._dead
@property def completed(self): self._update_status() return self._completed
def new(self, func_or_exp, *args, **kwargs): """Add a new background job and start it in a separate thread.
There are two types of jobs which can be created:
1. Jobs based on expressions which can be passed to an eval() call. The expression must be given as a string. For example:
job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
The given expression is passed to eval(), along with the optional global/local dicts provided. If no dicts are given, they are extracted automatically from the caller's frame.
A Python statement is NOT a valid eval() expression. Basically, you can only use as an eval() argument something which can go on the right of an '=' sign and be assigned to a variable.
For example,"print 'hello'" is not valid, but '2+3' is.
2. Jobs given a function object, optionally passing additional positional arguments:
job_manager.new(myfunc, x, y)
The function is called with the given arguments.
If you need to pass keyword arguments to your function, you must supply them as a dict named kw:
job_manager.new(myfunc, x, y, kw=dict(z=1))
The reason for this asymmetry is that the new() method needs to maintain access to its own keywords, and this prevents name collisions between arguments to new() and arguments to your own functions.
In both cases, the result is stored in the job.result field of the background job object.
You can set `daemon` attribute of the thread by giving the keyword argument `daemon`.
Notes and caveats:
1. All threads running share the same standard output. Thus, if your background jobs generate output, it will come out on top of whatever you are currently writing. For this reason, background jobs are best used with silent functions which simply return their output.
2. Threads also all work within the same global namespace, and this system does not lock interactive variables. So if you send job to the background which operates on a mutable object for a long time, and start modifying that same mutable object interactively (or in another backgrounded job), all sorts of bizarre behaviour will occur.
3. If a background job is spending a lot of time inside a C extension module which does not release the Python Global Interpreter Lock (GIL), this will block the IPython prompt. This is simply because the Python interpreter can only switch between threads at Python bytecodes. While the execution is inside C code, the interpreter must simply wait unless the extension module releases the GIL.
4. There is no way, due to limitations in the Python threads library, to kill a thread once it has started.""" if callable(func_or_exp): kw = kwargs.get('kw',{}) job = BackgroundJobFunc(func_or_exp,*args,**kw) elif isinstance(func_or_exp, str): if not args: frame = sys._getframe(1) glob, loc = frame.f_globals, frame.f_locals elif len(args)==1: glob = loc = args[0] elif len(args)==2: glob,loc = args else: raise ValueError( 'Expression jobs take at most 2 args (globals,locals)') job = BackgroundJobExpr(func_or_exp, glob, loc) else: raise TypeError('invalid args for new job')
if kwargs.get('daemon', False): job.daemon = True job.num = self._current_job_id self._current_job_id += 1 self.running.append(job) self.all[job.num] = job debug('Starting job # %s in a separate thread.' % job.num) job.start() return job
def __getitem__(self, job_key): num = job_key if isinstance(job_key, int) else job_key.num return self.all[num]
def __call__(self): """An alias to self.status(),
This allows you to simply call a job manager instance much like the Unix `jobs` shell command."""
return self.status()
def _update_status(self): """Update the status of the job lists.
This method moves finished jobs to one of two lists: - self.completed: jobs which completed successfully - self.dead: jobs which finished but died.
It also copies those jobs to corresponding _report lists. These lists are used to report jobs completed/dead since the last update, and are then cleared by the reporting function after each call."""
# Status codes srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead # State lists, use the actual lists b/c the public names are properties # that call this very function on access running, completed, dead = self._running, self._completed, self._dead
# Now, update all state lists for num, job in enumerate(running): stat = job.stat_code if stat == srun: continue elif stat == scomp: completed.append(job) self._comp_report.append(job) running[num] = False elif stat == sdead: dead.append(job) self._dead_report.append(job) running[num] = False # Remove dead/completed jobs from running list running[:] = filter(None, running)
def _group_report(self,group,name): """Report summary for a given job group.
Return True if the group had any elements."""
if group: print('%s jobs:' % name) for job in group: print('%s : %s' % (job.num,job)) print() return True
def _group_flush(self,group,name): """Flush a given job group
Return True if the group had any elements."""
njobs = len(group) if njobs: plural = {1:''}.setdefault(njobs,'s') print('Flushing %s %s job%s.' % (njobs,name,plural)) group[:] = [] return True def _status_new(self): """Print the status of newly finished jobs.
Return True if any new jobs are reported.
This call resets its own state every time, so it only reports jobs which have finished since the last time it was called."""
self._update_status() new_comp = self._group_report(self._comp_report, 'Completed') new_dead = self._group_report(self._dead_report, 'Dead, call jobs.traceback() for details') self._comp_report[:] = [] self._dead_report[:] = [] return new_comp or new_dead def status(self,verbose=0): """Print a status of all jobs currently being managed."""
self._update_status() self._group_report(self.running,'Running') self._group_report(self.completed,'Completed') self._group_report(self.dead,'Dead') # Also flush the report queues self._comp_report[:] = [] self._dead_report[:] = []
def remove(self,num): """Remove a finished (completed or dead) job."""
try: job = self.all[num] except KeyError: error('Job #%s not found' % num) else: stat_code = job.stat_code if stat_code == self._s_running: error('Job #%s is still running, it can not be removed.' % num) return elif stat_code == self._s_completed: self.completed.remove(job) elif stat_code == self._s_dead: self.dead.remove(job)
def flush(self): """Flush all finished jobs (completed and dead) from lists.
Running jobs are never flushed.
It first calls _status_new(), to update info. If any jobs have completed since the last _status_new() call, the flush operation aborts."""
# Remove the finished jobs from the master dict alljobs = self.all for job in self.completed+self.dead: del(alljobs[job.num])
# Now flush these lists completely fl_comp = self._group_flush(self.completed, 'Completed') fl_dead = self._group_flush(self.dead, 'Dead') if not (fl_comp or fl_dead): print('No jobs to flush.')
def result(self,num): """result(N) -> return the result of job N.""" try: return self.all[num].result except KeyError: error('Job #%s not found' % num)
def _traceback(self, job): num = job if isinstance(job, int) else job.num try: self.all[num].traceback() except KeyError: error('Job #%s not found' % num)
def traceback(self, job=None): if job is None: self._update_status() for deadjob in self.dead: print("Traceback for: %r" % deadjob) self._traceback(deadjob) print() else: self._traceback(job)
class BackgroundJobBase(threading.Thread): """Base class to build BackgroundJob classes.
The derived classes must implement:
- Their own __init__, since the one here raises NotImplementedError. The derived constructor must call self._init() at the end, to provide common initialization.
- A strform attribute used in calls to __str__.
- A call() method, which will make the actual execution call and must return a value to be held in the 'result' field of the job object. """
# Class constants for status, in string and as numerical codes (when # updating jobs lists, we don't want to do string comparisons). This will # be done at every user prompt, so it has to be as fast as possible stat_created = 'Created'; stat_created_c = 0 stat_running = 'Running'; stat_running_c = 1 stat_completed = 'Completed'; stat_completed_c = 2 stat_dead = 'Dead (Exception), call jobs.traceback() for details' stat_dead_c = -1
def __init__(self): """Must be implemented in subclasses.
Subclasses must call :meth:`_init` for standard initialisation. """ raise NotImplementedError("This class can not be instantiated directly.")
def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call','strform']: assert hasattr(self,attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not completed>' # reuse the ipython traceback handler if we can get to it, otherwise # make a new one try: make_tb = get_ipython().InteractiveTB.text except: make_tb = AutoFormattedTB( mode="Context", color_scheme="nocolor", tb_offset=1 ).text # Note that the actual API for text() requires the three args to be # passed in, so we wrap it in a simple lambda. self._make_tb = lambda : make_tb(None, None, None)
# Hold a formatted traceback if one is generated. self._tb = None threading.Thread.__init__(self)
def __str__(self): return self.strform
def __repr__(self): return '<BackgroundJob #%d: %s>' % (self.num, self.strform)
def traceback(self): print(self._tb) def run(self): try: self.status = BackgroundJobBase.stat_running self.stat_code = BackgroundJobBase.stat_running_c self.result = self.call() except: self.status = BackgroundJobBase.stat_dead self.stat_code = BackgroundJobBase.stat_dead_c self.finished = None self.result = ('<BackgroundJob died, call jobs.traceback() for details>') self._tb = self._make_tb() else: self.status = BackgroundJobBase.stat_completed self.stat_code = BackgroundJobBase.stat_completed_c self.finished = True
class BackgroundJobExpr(BackgroundJobBase): """Evaluate an expression as a background job (uses a separate thread)."""
def __init__(self, expression, glob=None, loc=None): """Create a new job from a string which can be fed to eval().
global/locals dicts can be provided, which will be passed to the eval call."""
# fail immediately if the given expression can't be compiled self.code = compile(expression,'<BackgroundJob compilation>','eval') glob = {} if glob is None else glob loc = {} if loc is None else loc self.expression = self.strform = expression self.glob = glob self.loc = loc self._init() def call(self): return eval(self.code,self.glob,self.loc)
class BackgroundJobFunc(BackgroundJobBase): """Run a function call as a background job (uses a separate thread)."""
def __init__(self, func, *args, **kwargs): """Create a new job from a callable object.
Any positional arguments and keyword args given to this constructor after the initial callable are passed directly to it."""
if not callable(func): raise TypeError( 'first argument to BackgroundJobFunc must be callable') self.func = func self.args = args self.kwargs = kwargs # The string form will only include the function passed, because # generating string representations of the arguments is a potentially # _very_ expensive operation (e.g. with large arrays). self.strform = str(func) self._init()
def call(self): return self.func(*self.args, **self.kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102""" Utilities for accessing the platform's clipboard."""
import osimport subprocess
from IPython.core.error import TryNextimport IPython.utils.py3compat as py3compat
class ClipboardEmpty(ValueError): pass
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 text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310# -*- coding: utf-8 -*-"""Provides a reload() function that acts recursively.
Python's normal :func:`python:reload` function only reloads the module that it'spassed. The :func:`reload` function in this module also reloads everythingimported from that module, which is useful when you're changing files deepinside a package.
To use this as your default reload function, type this::
import builtins from IPython.lib import deepreload builtins.reload = deepreload.reload
A reference to the original :func:`python:reload` is stored in this module as:data:`original_reload`, so you can restore it later.
This code is almost entirely based on knee.py, which is a Pythonre-implementation of hierarchical module import."""#*****************************************************************************# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.#*****************************************************************************
import builtins as builtin_modfrom contextlib import contextmanagerimport importlibimport sys
from types import ModuleTypefrom warnings import warnimport types
original_import = builtin_mod.__import__
@contextmanagerdef replace_import_hook(new_import): saved_import = builtin_mod.__import__ builtin_mod.__import__ = new_import try: yield finally: builtin_mod.__import__ = saved_import
def get_parent(globals, level): """ parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes from the module foo.bar.bat (not itself a package), this returns the sys.modules entry for foo.bar. If globals is from a package's __init__.py, the package's entry in sys.modules is returned.
If globals doesn't come from a package or a module in a package, or a corresponding entry is not found in sys.modules, None is returned. """ orig_level = level
if not level or not isinstance(globals, dict): return None, ''
pkgname = globals.get('__package__', None)
if pkgname is not None: # __package__ is set, so use it if not hasattr(pkgname, 'rindex'): raise ValueError('__package__ set to non-string') if len(pkgname) == 0: if level > 0: raise ValueError('Attempted relative import in non-package') return None, '' name = pkgname else: # __package__ not set, so figure it out and set it if '__name__' not in globals: return None, '' modname = globals['__name__']
if '__path__' in globals: # __path__ is set, so modname is already the package name globals['__package__'] = name = modname else: # Normal module, so work out the package name if any lastdot = modname.rfind('.') if lastdot < 0 < level: raise ValueError("Attempted relative import in non-package") if lastdot < 0: globals['__package__'] = None return None, '' globals['__package__'] = name = modname[:lastdot]
dot = len(name) for x in range(level, 1, -1): try: dot = name.rindex('.', 0, dot) except ValueError as e: raise ValueError("attempted relative import beyond top-level " "package") from e name = name[:dot]
try: parent = sys.modules[name] except BaseException as e: if orig_level < 1: warn("Parent module '%.200s' not found while handling absolute " "import" % name) parent = None else: raise SystemError("Parent module '%.200s' not loaded, cannot " "perform relative import" % name) from e
# We expect, but can't guarantee, if parent != None, that: # - parent.__name__ == name # - parent.__dict__ is globals # If this is violated... Who cares? return parent, name
def load_next(mod, altmod, name, buf): """ mod, name, buf = load_next(mod, altmod, name, buf)
altmod is either None or same as mod """
if len(name) == 0: # completely empty module name should only happen in # 'from . import' (or '__import__("")') return mod, None, buf
dot = name.find('.') if dot == 0: raise ValueError('Empty module name')
if dot < 0: subname = name next = None else: subname = name[:dot] next = name[dot+1:]
if buf != '': buf += '.' buf += subname
result = import_submodule(mod, subname, buf) if result is None and mod != altmod: result = import_submodule(altmod, subname, subname) if result is not None: buf = subname
if result is None: raise ImportError("No module named %.200s" % name)
return result, next, buf
# Need to keep track of what we've already reloaded to prevent cyclic evilfound_now = {}
def import_submodule(mod, subname, fullname): """m = import_submodule(mod, subname, fullname)""" # Require: # if mod == None: subname == fullname # else: mod.__name__ + "." + subname == fullname
global found_now if fullname in found_now and fullname in sys.modules: m = sys.modules[fullname] else: print('Reloading', fullname) found_now[fullname] = 1 oldm = sys.modules.get(fullname, None) try: if oldm is not None: m = importlib.reload(oldm) else: m = importlib.import_module(subname, mod) except: # load_module probably removed name from modules because of # the error. Put back the original module object. if oldm: sys.modules[fullname] = oldm raise
add_submodule(mod, m, fullname, subname)
return m
def add_submodule(mod, submod, fullname, subname): """mod.{subname} = submod""" if mod is None: return #Nothing to do here.
if submod is None: submod = sys.modules[fullname]
setattr(mod, subname, submod)
return
def ensure_fromlist(mod, fromlist, buf, recursive): """Handle 'from module import a, b, c' imports.""" if not hasattr(mod, '__path__'): return for item in fromlist: if not hasattr(item, 'rindex'): raise TypeError("Item in ``from list'' not a string") if item == '*': if recursive: continue # avoid endless recursion try: all = mod.__all__ except AttributeError: pass else: ret = ensure_fromlist(mod, all, buf, 1) if not ret: return 0 elif not hasattr(mod, item): import_submodule(mod, item, buf + '.' + item)
def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1): """Replacement for __import__()""" parent, buf = get_parent(globals, level)
head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
tail = head while name: tail, name, buf = load_next(tail, tail, name, buf)
# If tail is None, both get_parent and load_next found # an empty module name: someone called __import__("") or # doctored faulty bytecode if tail is None: raise ValueError('Empty module name')
if not fromlist: return head
ensure_fromlist(tail, fromlist, buf, 0) return tail
modules_reloading = {}
def deep_reload_hook(m): """Replacement for reload().""" # Hardcode this one as it would raise a NotImplementedError from the # bowels of Python and screw up the import machinery after. # unlike other imports the `exclude` list already in place is not enough.
if m is types: return m if not isinstance(m, ModuleType): raise TypeError("reload() argument must be module")
name = m.__name__
if name not in sys.modules: raise ImportError("reload(): module %.200s not in sys.modules" % name)
global modules_reloading try: return modules_reloading[name] except: modules_reloading[name] = m
try: newm = importlib.reload(m) except: sys.modules[name] = m raise finally: modules_reloading.clear() return newm
# Save the original hooksoriginal_reload = importlib.reload
# Replacement for reload()def reload( module, exclude=( *sys.builtin_module_names, "sys", "os.path", "builtins", "__main__", "numpy", "numpy._globals", ),): """Recursively reload all modules used in the given module. Optionally takes a list of modules to exclude from reloading. The default exclude list contains modules listed in sys.builtin_module_names with additional sys, os.path, builtins and __main__, to prevent, e.g., resetting display, exception, and io hooks. """ global found_now for i in exclude: found_now[i] = 1 try: with replace_import_hook(deep_import_hook): return deep_reload_hook(module) finally: found_now = {}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672"""Module for interactive demos using IPython.
This module implements a few classes for running Python scripts interactivelyin IPython for demonstrations. With very simple markup (a few tags incomments), you can control points where the script stops executing and returnscontrol to IPython.
Provided classes----------------
The classes are (see their docstrings for further details):
- Demo: pure python demos
- IPythonDemo: demos with input to be processed by IPython as if it had been typed interactively (so magics work, as well as any other special syntax you may have added via input prefilters).
- LineDemo: single-line version of the Demo class. These demos are executed one line at a time, and require no markup.
- IPythonLineDemo: IPython version of the LineDemo class (the demo is executed a line at a time, but processed via IPython).
- ClearMixin: mixin to make Demo classes with less visual clutter. It declares an empty marquee and a pre_cmd that clears the screen before each block (see Subclassing below).
- ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo classes.
Inheritance diagram:
.. inheritance-diagram:: IPython.lib.demo :parts: 3
Subclassing-----------
The classes here all include a few methods meant to make customization bysubclassing more convenient. Their docstrings below have some more details:
- highlight(): format every block and optionally highlight comments and docstring content.
- marquee(): generates a marquee to provide visible on-screen markers at each block start and end.
- pre_cmd(): run right before the execution of each block.
- post_cmd(): run right after the execution of each block. If the block raises an exception, this is NOT called.
Operation---------
The file is run in its own empty namespace (though you can pass it a string ofarguments as if in a command line environment, and it will see those assys.argv). But at each stop, the global IPython namespace is updated with thecurrent internal demo namespace, so you can work interactively with the dataaccumulated so far.
By default, each block of code is printed (with syntax highlighting) beforeexecuting it and you have to confirm execution. This is intended to show thecode to an audience first so you can discuss it, and only proceed withexecution once you agree. There are a few tags which allow you to modify thisbehavior.
The supported tags are:
# <demo> stop
Defines block boundaries, the points where IPython stops execution of the file and returns to the interactive prompt.
You can optionally mark the stop tag with extra dashes before and after the word 'stop', to help visually distinguish the blocks in a text editor:
# <demo> --- stop ---
# <demo> silent
Make a block execute silently (and hence automatically). Typically used in cases where you have some boilerplate or initialization code which you need executed but do not want to be seen in the demo.
# <demo> auto
Make a block execute automatically, but still being printed. Useful for simple code which does not warrant discussion, since it avoids the extra manual confirmation.
# <demo> auto_all
This tag can _only_ be in the first block, and if given it overrides the individual auto tags to make the whole demo fully automatic (no block asks for confirmation). It can also be given at creation time (or the attribute set later) to override what's in the file.
While _any_ python file can be run as a Demo instance, if there are no stoptags the whole file will run in a single block (no different that callingfirst %pycat and then %run). The minimal markup to make this useful is toplace a set of stop tags; the other tags are only there to let you fine-tunethe execution.
This is probably best explained with the simple example file below. You cancopy this into a file named ex_demo.py, and try running it via::
from IPython.lib.demo import Demo d = Demo('ex_demo.py') d()
Each time you call the demo object, it runs the next block. The demo objecthas a few useful methods for navigation, like again(), edit(), jump(), seek()and back(). It can be reset for a new run via reset() or reloaded from disk(in case you've edited the source) via reload(). See their docstrings below.
Note: To make this simpler to explore, a file called "demo-exercizer.py" hasbeen added to the "docs/examples/core" directory. Just cd to this directory inan IPython session, and type::
%run demo-exercizer.py
and then follow the directions.
Example-------
The following is a very simple example of a valid demo file.
::
#################### EXAMPLE DEMO <ex_demo.py> ############################### '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
print('Hello, welcome to an interactive IPython demo.')
# The mark below defines a block boundary, which is a point where IPython will # stop execution and return to the interactive prompt. The dashes are actually # optional and used only as a visual aid to clearly separate blocks while # editing the demo code. # <demo> stop
x = 1 y = 2
# <demo> stop
# the mark below makes this block as silent # <demo> silent
print('This is a silent block, which gets executed but not printed.')
# <demo> stop # <demo> auto print('This is an automatic block.') print('It is executed without asking for confirmation, but printed.') z = x + y
print('z =', x)
# <demo> stop # This is just another normal block. print('z is now:', z)
print('bye!') ################### END EXAMPLE DEMO <ex_demo.py> ############################"""
#*****************************************************************************# Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>## Distributed under the terms of the BSD License. The full license is in# the file COPYING, distributed as part of this software.##*****************************************************************************
import osimport reimport shleximport sysimport pygmentsfrom pathlib import Path
from IPython.utils.text import marqueefrom IPython.utils import openpyfrom IPython.utils import py3compat__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
class DemoError(Exception): pass
def re_mark(mark): return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
class Demo:
re_stop = re_mark(r'-*\s?stop\s?-*') re_silent = re_mark('silent') re_auto = re_mark('auto') re_auto_all = re_mark('auto_all')
def __init__(self,src,title='',arg_str='',auto_all=None, format_rst=False, formatter='terminal', style='default'): """Make a new demo object. To run the demo, simply call the object.
See the module docstring for full details and an example (you can use IPython.Demo? in IPython to see it).
Inputs:
- src is either a file, or file-like object, or a string that can be resolved to a filename.
Optional inputs:
- title: a string to use as the demo name. Of most use when the demo you are making comes from an object that has no filename, or if you want an alternate denotation distinct from the filename.
- arg_str(''): a string of arguments, internally converted to a list just like sys.argv, so the demo script can see a similar environment.
- auto_all(None): global flag to run all blocks automatically without confirmation. This attribute overrides the block-level tags and applies to the whole demo. It is an attribute of the object, and can be changed at runtime simply by reassigning it to a boolean value.
- format_rst(False): a bool to enable comments and doc strings formatting with pygments rst lexer
- formatter('terminal'): a string of pygments formatter name to be used. Useful values for terminals: terminal, terminal256, terminal16m
- style('default'): a string of pygments style name to be used. """ if hasattr(src, "read"): # It seems to be a file or a file-like object self.fname = "from a file-like object" if title == '': self.title = "from a file-like object" else: self.title = title else: # Assume it's a string or something that can be converted to one self.fname = src if title == '': (filepath, filename) = os.path.split(src) self.title = filename else: self.title = title self.sys_argv = [src] + shlex.split(arg_str) self.auto_all = auto_all self.src = src
try: ip = get_ipython() # this is in builtins whenever IPython is running self.inside_ipython = True except NameError: self.inside_ipython = False
if self.inside_ipython: # get a few things from ipython. While it's a bit ugly design-wise, # it ensures that things like color scheme and the like are always in # sync with the ipython mode being used. This class is only meant to # be used inside ipython anyways, so it's OK. self.ip_ns = ip.user_ns self.ip_colorize = ip.pycolorize self.ip_showtb = ip.showtraceback self.ip_run_cell = ip.run_cell self.shell = ip
self.formatter = pygments.formatters.get_formatter_by_name(formatter, style=style) self.python_lexer = pygments.lexers.get_lexer_by_name("py3") self.format_rst = format_rst if format_rst: self.rst_lexer = pygments.lexers.get_lexer_by_name("rst")
# load user data and initialize data structures self.reload()
def fload(self): """Load file object.""" # read data and parse into blocks if hasattr(self, 'fobj') and self.fobj is not None: self.fobj.close() if hasattr(self.src, "read"): # It seems to be a file or a file-like object self.fobj = self.src else: # Assume it's a string or something that can be converted to one self.fobj = openpy.open(self.fname)
def reload(self): """Reload source from disk and initialize state.""" self.fload()
self.src = "".join(openpy.strip_encoding_cookie(self.fobj)) src_b = [b.strip() for b in self.re_stop.split(self.src) if b] self._silent = [bool(self.re_silent.findall(b)) for b in src_b] self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
# if auto_all is not given (def. None), we read it from the file if self.auto_all is None: self.auto_all = bool(self.re_auto_all.findall(src_b[0])) else: self.auto_all = bool(self.auto_all)
# Clean the sources from all markup so it doesn't get displayed when # running the demo src_blocks = [] auto_strip = lambda s: self.re_auto.sub('',s) for i,b in enumerate(src_b): if self._auto[i]: src_blocks.append(auto_strip(b)) else: src_blocks.append(b) # remove the auto_all marker src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
self.nblocks = len(src_blocks) self.src_blocks = src_blocks
# also build syntax-highlighted source self.src_blocks_colored = list(map(self.highlight,self.src_blocks))
# ensure clean namespace and seek offset self.reset()
def reset(self): """Reset the namespace and seek pointer to restart the demo""" self.user_ns = {} self.finished = False self.block_index = 0
def _validate_index(self,index): if index<0 or index>=self.nblocks: raise ValueError('invalid block index %s' % index)
def _get_index(self,index): """Get the current block index, validating and checking status.
Returns None if the demo is finished"""
if index is None: if self.finished: print('Demo finished. Use <demo_name>.reset() if you want to rerun it.') return None index = self.block_index else: self._validate_index(index) return index
def seek(self,index): """Move the current seek pointer to the given block.
You can use negative indices to seek from the end, with identical semantics to those of Python lists.""" if index<0: index = self.nblocks + index self._validate_index(index) self.block_index = index self.finished = False
def back(self,num=1): """Move the seek pointer back num blocks (default is 1).""" self.seek(self.block_index-num)
def jump(self,num=1): """Jump a given number of blocks relative to the current one.
The offset can be positive or negative, defaults to 1.""" self.seek(self.block_index+num)
def again(self): """Move the seek pointer back one block and re-execute.""" self.back(1) self()
def edit(self,index=None): """Edit a block.
If no number is given, use the last block executed.
This edits the in-memory copy of the demo, it does NOT modify the original source file. If you want to do that, simply open the file in an editor and use reload() when you make changes to the file. This method is meant to let you change a block during a demonstration for explanatory purposes, without damaging your original script."""
index = self._get_index(index) if index is None: return # decrease the index by one (unless we're at the very beginning), so # that the default demo.edit() call opens up the sblock we've last run if index>0: index -= 1
filename = self.shell.mktempfile(self.src_blocks[index]) self.shell.hooks.editor(filename, 1) with open(Path(filename), "r", encoding="utf-8") as f: new_block = f.read() # update the source and colored block self.src_blocks[index] = new_block self.src_blocks_colored[index] = self.highlight(new_block) self.block_index = index # call to run with the newly edited index self()
def show(self,index=None): """Show a single block on screen"""
index = self._get_index(index) if index is None: return
print(self.marquee('<%s> block # %s (%s remaining)' % (self.title,index,self.nblocks-index-1))) print(self.src_blocks_colored[index]) sys.stdout.flush()
def show_all(self): """Show entire demo on screen, block by block"""
fname = self.title title = self.title nblocks = self.nblocks silent = self._silent marquee = self.marquee for index,block in enumerate(self.src_blocks_colored): if silent[index]: print(marquee('<%s> SILENT block # %s (%s remaining)' % (title,index,nblocks-index-1))) else: print(marquee('<%s> block # %s (%s remaining)' % (title,index,nblocks-index-1))) print(block, end=' ') sys.stdout.flush()
def run_cell(self,source): """Execute a string with one or more lines of code"""
exec(source, self.user_ns)
def __call__(self,index=None): """run a block of the demo.
If index is given, it should be an integer >=1 and <= nblocks. This means that the calling convention is one off from typical Python lists. The reason for the inconsistency is that the demo always prints 'Block n/N, and N is the total, so it would be very odd to use zero-indexing here."""
index = self._get_index(index) if index is None: return try: marquee = self.marquee next_block = self.src_blocks[index] self.block_index += 1 if self._silent[index]: print(marquee('Executing silent block # %s (%s remaining)' % (index,self.nblocks-index-1))) else: self.pre_cmd() self.show(index) if self.auto_all or self._auto[index]: print(marquee('output:')) else: print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ') ans = py3compat.input().strip() if ans: print(marquee('Block NOT executed')) return try: save_argv = sys.argv sys.argv = self.sys_argv self.run_cell(next_block) self.post_cmd() finally: sys.argv = save_argv
except: if self.inside_ipython: self.ip_showtb(filename=self.fname) else: if self.inside_ipython: self.ip_ns.update(self.user_ns)
if self.block_index == self.nblocks: mq1 = self.marquee('END OF DEMO') if mq1: # avoid spurious print if empty marquees are used print() print(mq1) print(self.marquee('Use <demo_name>.reset() if you want to rerun it.')) self.finished = True
# These methods are meant to be overridden by subclasses who may wish to # customize the behavior of of their demos. def marquee(self,txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'.""" return marquee(txt,width,mark)
def pre_cmd(self): """Method called before executing each block.""" pass
def post_cmd(self): """Method called after executing each block.""" pass
def highlight(self, block): """Method called on each block to highlight it content""" tokens = pygments.lex(block, self.python_lexer) if self.format_rst: from pygments.token import Token toks = [] for token in tokens: if token[0] == Token.String.Doc and len(token[1]) > 6: toks += pygments.lex(token[1][:3], self.python_lexer) # parse doc string content by rst lexer toks += pygments.lex(token[1][3:-3], self.rst_lexer) toks += pygments.lex(token[1][-3:], self.python_lexer) elif token[0] == Token.Comment.Single: toks.append((Token.Comment.Single, token[1][0])) # parse comment content by rst lexer # remove the extra newline added by rst lexer toks += list(pygments.lex(token[1][1:], self.rst_lexer))[:-1] else: toks.append(token) tokens = toks return pygments.format(tokens, self.formatter)
class IPythonDemo(Demo): """Class for interactive demos with IPython's input processing applied.
This subclasses Demo, but instead of executing each block by the Python interpreter (via exec), it actually calls IPython on it, so that any input filters which may be in place are applied to the input block.
If you have an interactive environment which exposes special input processing, you can use this class instead to write demo scripts which operate exactly as if you had typed them interactively. The default Demo class requires the input to be valid, pure Python code. """
def run_cell(self,source): """Execute a string with one or more lines of code"""
self.shell.run_cell(source)
class LineDemo(Demo): """Demo where each line is executed as a separate block.
The input script should be valid Python code.
This class doesn't require any markup at all, and it's meant for simple scripts (with no nesting or any kind of indentation) which consist of multiple lines of input to be executed, one at a time, as if they had been typed in the interactive prompt.
Note: the input can not have *any* indentation, which means that only single-lines of input are accepted, not even function definitions are valid."""
def reload(self): """Reload source from disk and initialize state.""" # read data and parse into blocks self.fload() lines = self.fobj.readlines() src_b = [l for l in lines if l.strip()] nblocks = len(src_b) self.src = ''.join(lines) self._silent = [False]*nblocks self._auto = [True]*nblocks self.auto_all = True self.nblocks = nblocks self.src_blocks = src_b
# also build syntax-highlighted source self.src_blocks_colored = list(map(self.highlight,self.src_blocks))
# ensure clean namespace and seek offset self.reset()
class IPythonLineDemo(IPythonDemo,LineDemo): """Variant of the LineDemo class whose input is processed by IPython.""" pass
class ClearMixin: """Use this mixin to make Demo classes with less visual clutter.
Demos using this mixin will clear the screen before every block and use blank marquees.
Note that in order for the methods defined here to actually override those of the classes it's mixed with, it must go /first/ in the inheritance tree. For example:
class ClearIPDemo(ClearMixin,IPythonDemo): pass
will provide an IPythonDemo class with the mixin's features. """
def marquee(self,txt='',width=78,mark='*'): """Blank marquee that returns '' no matter what the input.""" return ''
def pre_cmd(self): """Method called before executing each block.
This one simply clears the screen.""" from IPython.utils.terminal import _term_clear _term_clear()
class ClearDemo(ClearMixin,Demo): pass
class ClearIPDemo(ClearMixin,IPythonDemo): pass
def slide(file_path, noclear=False, format_rst=True, formatter="terminal", style="native", auto_all=False, delimiter='...'): if noclear: demo_class = Demo else: demo_class = ClearDemo demo = demo_class(file_path, format_rst=format_rst, formatter=formatter, style=style, auto_all=auto_all) while not demo.finished: demo() try: py3compat.input('\n' + delimiter) except KeyboardInterrupt: exit(1)
if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Run python demos') parser.add_argument('--noclear', '-C', action='store_true', help='Do not clear terminal on each slide') parser.add_argument('--rst', '-r', action='store_true', help='Highlight comments and dostrings as rst') parser.add_argument('--formatter', '-f', default='terminal', help='pygments formatter name could be: terminal, ' 'terminal256, terminal16m') parser.add_argument('--style', '-s', default='default', help='pygments style name') parser.add_argument('--auto', '-a', action='store_true', help='Run all blocks automatically without' 'confirmation') parser.add_argument('--delimiter', '-d', default='...', help='slides delimiter added after each slide run') parser.add_argument('file', nargs=1, help='python demo file') args = parser.parse_args() slide(args.file[0], noclear=args.noclear, format_rst=args.rst, formatter=args.formatter, style=args.style, auto_all=args.auto, delimiter=args.delimiter)lib/python3.12/site-packages/IPython/core/__init__.pyAdded
lib/python3.12/site-packages/IPython/core/alias.pyAdded+268
lib/python3.12/site-packages/IPython/core/application.pyAdded+492
lib/python3.12/site-packages/IPython/core/async_helpers.pyAdded+150
lib/python3.12/site-packages/IPython/core/autocall.pyAdded+70
lib/python3.12/site-packages/IPython/core/builtin_trap.pyAdded+93
lib/python3.12/site-packages/IPython/core/completer.pyAdded
lib/python3.12/site-packages/IPython/core/debugger.pyAdded+1376
lib/python3.12/site-packages/IPython/core/debugger_backport.pyAdded+206
lib/python3.12/site-packages/IPython/core/display.pyAdded+1266
lib/python3.12/site-packages/IPython/core/display_functions.pyAdded+371
lib/python3.12/site-packages/IPython/core/display_trap.pyAdded+74
lib/python3.12/site-packages/IPython/core/displayhook.pyAdded+346
lib/python3.12/site-packages/IPython/core/doctb.pyAdded+445
lib/python3.12/site-packages/IPython/core/events.pyAdded+172
lib/python3.12/site-packages/IPython/core/formatters.pyAdded+1090
lib/python3.12/site-packages/IPython/core/historyapp.pyAdded+158
lib/python3.12/site-packages/IPython/core/inputtransformer2.pyAdded+898
lib/python3.12/site-packages/IPython/core/interactiveshell.pyAdded
lib/python3.12/site-packages/IPython/core/macro.pyAdded+53
lib/python3.12/site-packages/IPython/core/magic_arguments.pyAdded+312
lib/python3.12/site-packages/IPython/core/oinspect.pyAdded+1215
lib/python3.12/site-packages/IPython/core/page.pyAdded+348
lib/python3.12/site-packages/IPython/core/payload.pyAdded+54
lib/python3.12/site-packages/IPython/core/payloadpage.pyAdded+41
lib/python3.12/site-packages/IPython/core/prefilter.pyAdded+707
lib/python3.12/site-packages/IPython/core/profileapp.pyAdded+315
lib/python3.12/site-packages/IPython/core/profiledir.pyAdded+244
lib/python3.12/site-packages/IPython/core/pylabtools.pyAdded+514
lib/python3.12/site-packages/IPython/core/shellapp.pyAdded+500
lib/python3.12/site-packages/IPython/core/splitinput.pyAdded+155
lib/python3.12/site-packages/IPython/core/tips.pyAdded+128
lib/python3.12/site-packages/IPython/core/ultratb.pyAdded+1263
lib/python3.12/site-packages/IPython/core/usage.pyAdded+341
lib/python3.12/site-packages/IPython/lib/__init__.pyAdded+11
lib/python3.12/site-packages/IPython/lib/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/backgroundjobs.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/clipboard.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/deepreload.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/demo.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/display.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/editorhooks.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/guisupport.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/latextools.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/lexers.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/__pycache__/pretty.cpython-312.pycAdded
lib/python3.12/site-packages/IPython/lib/backgroundjobs.pyAdded+491
lib/python3.12/site-packages/IPython/lib/clipboard.pyAdded+102
lib/python3.12/site-packages/IPython/lib/deepreload.pyAdded+310
lib/python3.12/site-packages/IPython/lib/demo.pyAdded+672