Skip to content

Commit

Permalink
A Large number of code updates.
Browse files Browse the repository at this point in the history
Mostly starting to run ruff on the codebase excluding tests.
  • Loading branch information
Carreau committed Dec 20, 2024
1 parent 5fbc6d2 commit 7365aa0
Show file tree
Hide file tree
Showing 23 changed files with 245 additions and 284 deletions.
5 changes: 0 additions & 5 deletions IPython/core/debugger.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,11 +281,6 @@ def __init__(self, completekey=None, stdin=None, stdout=None, context=5, **kwarg
# module and add a few attributes needed for debugging
self.color_scheme_table = exception_colors()

# shorthands
C = coloransi.TermColors
cst = self.color_scheme_table


# Add a python parser so we can syntax highlight source while
# debugging.
self.parser = PyColorize.Parser(style=color_scheme)
Expand Down
1 change: 0 additions & 1 deletion IPython/core/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -937,7 +937,6 @@ def store_output(self, line_num: int) -> None:
"""
if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
return
lnum: int = line_num
output = self.output_hist_reprs[line_num]

with self.db_output_cache_lock:
Expand Down
63 changes: 31 additions & 32 deletions IPython/core/interactiveshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,18 @@ def __delitem__(self, key):
from IPython.utils.text import DollarFormatter, LSString, SList, format_screen
from IPython.core.oinspect import OInfo

from ast import Module

# we still need to run things using the asyncio eventloop, but there is no
# async integration

from .async_helpers import (
_asyncio_runner,
_curio_runner,
_pseudo_sync_runner,
_should_be_async,
_trio_runner,
)

sphinxify: Optional[Callable]

Expand Down Expand Up @@ -156,25 +168,10 @@ class ProvisionalWarning(DeprecationWarning):
"""
pass

from ast import Module

_assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
_single_targets_nodes = (ast.AugAssign, ast.AnnAssign)

#-----------------------------------------------------------------------------
# Await Helpers
#-----------------------------------------------------------------------------

# we still need to run things using the asyncio eventloop, but there is no
# async integration
from .async_helpers import (
_asyncio_runner,
_curio_runner,
_pseudo_sync_runner,
_should_be_async,
_trio_runner,
)

#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
Expand Down Expand Up @@ -220,7 +217,8 @@ def no_op(*a, **kw):
pass


class SpaceInInput(Exception): pass
class SpaceInInput(Exception):
pass


class SeparateUnicode(Unicode):
Expand All @@ -230,8 +228,9 @@ class SeparateUnicode(Unicode):
"""

def validate(self, obj, value):
if value == '0': value = ''
value = value.replace('\\n','\n')
if value == "0":
value = ""
value = value.replace("\\n", "\n")
return super(SeparateUnicode, self).validate(obj, value)


Expand Down Expand Up @@ -1572,7 +1571,7 @@ def push(self, variables, interactive=True):
for name in vlist:
try:
vdict[name] = eval(name, cf.f_globals, cf.f_locals)
except:
except Exception:
print('Could not get variable %s from %s' %
(name,cf.f_code.co_name))
else:
Expand Down Expand Up @@ -1731,7 +1730,7 @@ def _ofind(
obj = obj[int(part)]
else:
obj = getattr(obj, part)
except:
except Exception:
# Blanket except b/c some badly implemented objects
# allow __getattr__ to raise exceptions other than
# AttributeError, which then crashes IPython.
Expand Down Expand Up @@ -2022,7 +2021,7 @@ def wrapped(self,etype,value,tb,tb_offset=None):
try:
stb = handler(self,etype,value,tb,tb_offset=tb_offset)
return validate_stb(stb)
except:
except Exception:
# clear custom handler immediately
self.set_custom_exc((), None)
print("Custom TB Handler failed, unregistering", file=sys.stderr)
Expand Down Expand Up @@ -2215,7 +2214,7 @@ def showsyntaxerror(self, filename=None, running_compiled_code=False):
if filename and issubclass(etype, SyntaxError):
try:
value.filename = filename
except:
except Exception:
# Not the format we expect; leave it alone
pass

Expand Down Expand Up @@ -2861,7 +2860,7 @@ def user_expressions(self, expressions):
for key, expr in expressions.items():
try:
value = self._format_user_obj(eval(expr, global_ns, user_ns))
except:
except Exception:
value = self._user_obj_error()
out[key] = value
return out
Expand Down Expand Up @@ -2915,7 +2914,7 @@ def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False
try:
with fname.open("rb"):
pass
except:
except Exception:
warn('Could not open file <%s> for safe execution.' % fname)
return

Expand Down Expand Up @@ -2945,7 +2944,7 @@ def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False
raise
if not exit_ignore:
self.showtraceback(exception_only=True)
except:
except Exception:
if raise_exceptions:
raise
# tb offset is 2 because we wrap execfile
Expand Down Expand Up @@ -2973,7 +2972,7 @@ def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
try:
with fname.open("rb"):
pass
except:
except Exception:
warn('Could not open file <%s> for safe execution.' % fname)
return

Expand Down Expand Up @@ -3003,7 +3002,7 @@ def get_cells():
result.raise_error()
elif not result.success:
break
except:
except Exception:
if raise_exceptions:
raise
self.showtraceback()
Expand Down Expand Up @@ -3033,7 +3032,7 @@ def safe_run_module(self, mod_name, where):
except SystemExit as status:
if status.code:
raise
except:
except Exception:
self.showtraceback()
warn('Unknown failure executing module: <%s>' % mod_name)

Expand Down Expand Up @@ -3519,7 +3518,7 @@ def compare(code):
if softspace(sys.stdout, 0):
print()

except:
except Exception:
# It's possible to have exceptions raised here, typically by
# compilation of odd code (such as a naked 'return' outside a
# function) that did parse but isn't valid. Typically the exception
Expand Down Expand Up @@ -3591,7 +3590,7 @@ async def run_code(self, code_obj, result=None, *, async_=False):
if result is not None:
result.error_in_exec = value
self.CustomTB(etype, value, tb)
except:
except Exception:
if result is not None:
result.error_in_exec = sys.exc_info()[1]
self.showtraceback(running_compiled_code=True)
Expand Down Expand Up @@ -3657,12 +3656,12 @@ def enable_matplotlib(self, gui=None):
if not _matplotlib_manages_backends() and gui in (None, "auto"):
# Early import of backend_inline required for its side effect of
# calling _enable_matplotlib_integration()
import matplotlib_inline.backend_inline
import matplotlib_inline.backend_inline # noqa : F401

from IPython.core import pylabtools as pt
gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)

if gui != None:
if gui is not None:
# If we have our first gui selection, store it
if self.pylab_gui_select is None:
self.pylab_gui_select = gui
Expand Down
10 changes: 6 additions & 4 deletions IPython/core/magics/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -1456,10 +1456,12 @@ def macro(self, parameter_s=''):
return
macro = Macro(lines)
self.shell.define_macro(name, macro)
if 'q' not in opts :
print('Macro `%s` created. To execute, type its name (without quotes).' % name)
print('=== Macro contents: ===')
print(macro, end=' ')
if "q" not in opts:
print(
"Macro `%s` created. To execute, type its name (without quotes)." % name
)
print("=== Macro contents: ===")
print(macro, end=" ")

@magic_arguments.magic_arguments()
@magic_arguments.argument('output', type=str, default='', nargs='?',
Expand Down
6 changes: 3 additions & 3 deletions IPython/core/magics/osm.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,9 +425,9 @@ def cd(self, parameter_s=''):

if oldcwd != cwd:
dhist.append(cwd)
self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
if 'q' not in opts and not self.cd_force_quiet and self.shell.user_ns['_dh']:
print(self.shell.user_ns['_dh'][-1])
self.shell.db["dhist"] = compress_dhist(dhist)[-100:]
if "q" not in opts and not self.cd_force_quiet and self.shell.user_ns["_dh"]:
print(self.shell.user_ns["_dh"][-1])

@line_magic
def env(self, parameter_s=''):
Expand Down
1 change: 0 additions & 1 deletion IPython/core/oinspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,6 @@ def getsource(obj, oname='') -> Union[str,None]:
for attrname in ['fget', 'fset', 'fdel']:
fn = getattr(obj, attrname)
if fn is not None:
encoding = get_encoding(fn)
oname_prefix = ('%s.' % oname) if oname else ''
sources.append(''.join(('# ', oname_prefix, attrname)))
if inspect.isfunction(fn):
Expand Down
1 change: 0 additions & 1 deletion IPython/core/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,6 @@ def pager_page(strng, start=0, screen_lines=0, pager_cmd=None) -> None:
io.TextIOWrapper(proc.stdin, encoding="utf-8"), proc
)
try:
pager_encoding = pager.encoding or sys.stdout.encoding
pager.write(strng)
finally:
retval = pager.close()
Expand Down
4 changes: 2 additions & 2 deletions IPython/core/tests/refbug.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@

ip = get_ipython()

if '_refbug_cache' not in ip.user_ns:
ip.user_ns['_refbug_cache'] = []
if "_refbug_cache" not in ip.user_ns:
ip.user_ns["_refbug_cache"] = []


aglobal = 'Hello'
Expand Down
2 changes: 1 addition & 1 deletion IPython/core/tests/test_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def test_get_ipython_dir_4():
'IPYTHONDIR': None,
'XDG_CONFIG_HOME': XDG_TEST_DIR,
}), warnings.catch_warnings(record=True) as w:
ipdir = paths.get_ipython_dir()
_ipdir = paths.get_ipython_dir()

assert len(w) == 1
assert "Ignoring" in str(w[0])
Expand Down
18 changes: 8 additions & 10 deletions IPython/core/ultratb.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def _safe_string(value, what, func=str):
# Copied from cpython/Lib/traceback.py
try:
return func(value)
except:
except Exception:
return f"<{what} {func.__name__}() failed>"


Expand Down Expand Up @@ -730,9 +730,9 @@ def show_exception_only(self, etype, evalue):
def _some_str(self, value):
# Lifted from traceback.py
try:
return py3compat.cast_unicode(str(value))
return str(value)
except:
return u'<unprintable %s object>' % type(value).__name__
return "<unprintable %s object>" % type(value).__name__


class FrameInfo:
Expand Down Expand Up @@ -1048,7 +1048,7 @@ def format_exception(self, etype, evalue):
colors.excName,
etype_str,
colorsnormal,
py3compat.cast_unicode(evalue_str),
evalue_str,
),
*(
"{}{}".format(
Expand All @@ -1071,8 +1071,6 @@ def format_exception_as_a_whole(
This may be called multiple times by Python 3 exception chaining
(PEP 3134).
"""
# some locals
orig_etype = etype
try:
etype = etype.__name__ # type: ignore
except AttributeError:
Expand Down Expand Up @@ -1410,7 +1408,7 @@ class AutoFormattedTB(FormattedTB):
AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
try:
...
except:
except Exception:
AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
"""

Expand Down Expand Up @@ -1517,12 +1515,12 @@ def text_repr(value):
return pydoc.text.repr(value) # type: ignore[call-arg]
except KeyboardInterrupt:
raise
except:
except Exception:
try:
return repr(value)
except KeyboardInterrupt:
raise
except:
except Exception:
try:
# all still in an except block so we catch
# getattr raising
Expand All @@ -1535,7 +1533,7 @@ def text_repr(value):
return '%s instance' % text_repr(klass)
except KeyboardInterrupt:
raise
except:
except Exception:
return 'UNRECOVERABLE REPR FAILURE'


Expand Down
2 changes: 1 addition & 1 deletion IPython/lib/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ def show(self,index=None):
def show_all(self):
"""Show entire demo on screen, block by block"""

fname = self.title
self.title
title = self.title
nblocks = self.nblocks
silent = self._silent
Expand Down
Loading

0 comments on commit 7365aa0

Please sign in to comment.