[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -1,12 +1,13 @@
from __future__ import annotations
__all__ = [
"BaseExceptionGroup",
"ExceptionGroup",
"catch",
"format_exception",
"format_exception_only",
"print_exception",
"print_exc",
"suppress",
'BaseExceptionGroup',
'ExceptionGroup',
'catch',
'format_exception',
'format_exception_only',
'print_exception',
'print_exc',
'suppress',
]
import os
@ -24,7 +25,7 @@ if sys.version_info < (3, 11):
print_exception,
)
if os.getenv("EXCEPTIONGROUP_NO_PATCH") != "1":
if os.getenv('EXCEPTIONGROUP_NO_PATCH') != '1':
from . import _formatting # noqa: F401
BaseExceptionGroup.__module__ = __name__

View file

@ -2,10 +2,13 @@ from __future__ import annotations
import inspect
import sys
from collections.abc import Callable, Iterable, Mapping
from collections.abc import Callable
from collections.abc import Iterable
from collections.abc import Mapping
from contextlib import AbstractContextManager
from types import TracebackType
from typing import TYPE_CHECKING, Any
from typing import Any
from typing import TYPE_CHECKING
if sys.version_info < (3, 11):
from ._exceptions import BaseExceptionGroup
@ -52,7 +55,7 @@ class _Catcher:
if isinstance(exc, BaseExceptionGroup):
excgroup = exc
else:
excgroup = BaseExceptionGroup("", [exc])
excgroup = BaseExceptionGroup('', [exc])
new_exceptions: list[BaseException] = []
for exc_types, handler in self._handler_map.items():
@ -73,8 +76,8 @@ class _Catcher:
else:
if inspect.iscoroutine(result):
raise TypeError(
f"Error trying to handle {matched!r} with {handler!r}. "
"Exception handler must be a sync function."
f'Error trying to handle {matched!r} with {handler!r}. '
'Exception handler must be a sync function.',
) from exc
if not excgroup:
@ -84,7 +87,7 @@ class _Catcher:
if len(new_exceptions) == 1:
return new_exceptions[0]
return BaseExceptionGroup("", new_exceptions)
return BaseExceptionGroup('', new_exceptions)
elif (
excgroup and len(excgroup.exceptions) == 1 and excgroup.exceptions[0] is exc
):
@ -94,43 +97,43 @@ class _Catcher:
def catch(
__handlers: Mapping[type[BaseException] | Iterable[type[BaseException]], _Handler]
__handlers: Mapping[type[BaseException] | Iterable[type[BaseException]], _Handler],
) -> AbstractContextManager[None]:
if not isinstance(__handlers, Mapping):
raise TypeError("the argument must be a mapping")
raise TypeError('the argument must be a mapping')
handler_map: dict[
tuple[type[BaseException], ...], Callable[[BaseExceptionGroup]]
tuple[type[BaseException], ...], Callable[[BaseExceptionGroup]],
] = {}
for type_or_iterable, handler in __handlers.items():
iterable: tuple[type[BaseException]]
if isinstance(type_or_iterable, type) and issubclass(
type_or_iterable, BaseException
type_or_iterable, BaseException,
):
iterable = (type_or_iterable,)
elif isinstance(type_or_iterable, Iterable):
iterable = tuple(type_or_iterable)
else:
raise TypeError(
"each key must be either an exception classes or an iterable thereof"
'each key must be either an exception classes or an iterable thereof',
)
if not callable(handler):
raise TypeError("handlers must be callable")
raise TypeError('handlers must be callable')
for exc_type in iterable:
if not isinstance(exc_type, type) or not issubclass(
exc_type, BaseException
exc_type, BaseException,
):
raise TypeError(
"each key must be either an exception classes or an iterable "
"thereof"
'each key must be either an exception classes or an iterable '
'thereof',
)
if issubclass(exc_type, BaseExceptionGroup):
raise TypeError(
"catching ExceptionGroup with catch() is not allowed. "
"Use except instead."
'catching ExceptionGroup with catch() is not allowed. '
'Use except instead.',
)
handler_map[iterable] = handler

View file

@ -1,21 +1,28 @@
from __future__ import annotations
from collections.abc import Callable, Sequence
from collections.abc import Callable
from collections.abc import Sequence
from functools import partial
from inspect import getmro, isclass
from typing import TYPE_CHECKING, Generic, Type, TypeVar, cast, overload
from inspect import getmro
from inspect import isclass
from typing import cast
from typing import Generic
from typing import overload
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
if TYPE_CHECKING:
from typing import Self
_BaseExceptionT_co = TypeVar("_BaseExceptionT_co", bound=BaseException, covariant=True)
_BaseExceptionT = TypeVar("_BaseExceptionT", bound=BaseException)
_ExceptionT_co = TypeVar("_ExceptionT_co", bound=Exception, covariant=True)
_ExceptionT = TypeVar("_ExceptionT", bound=Exception)
_BaseExceptionT_co = TypeVar('_BaseExceptionT_co', bound=BaseException, covariant=True)
_BaseExceptionT = TypeVar('_BaseExceptionT', bound=BaseException)
_ExceptionT_co = TypeVar('_ExceptionT_co', bound=Exception, covariant=True)
_ExceptionT = TypeVar('_ExceptionT', bound=Exception)
def check_direct_subclass(
exc: BaseException, parents: tuple[type[BaseException]]
exc: BaseException, parents: tuple[type[BaseException]],
) -> bool:
for cls in getmro(exc.__class__)[:-1]:
if cls in parents:
@ -25,42 +32,42 @@ def check_direct_subclass(
def get_condition_filter(
condition: type[_BaseExceptionT]
| tuple[type[_BaseExceptionT], ...]
| Callable[[_BaseExceptionT_co], bool],
condition: type[_BaseExceptionT] |
tuple[type[_BaseExceptionT], ...] |
Callable[[_BaseExceptionT_co], bool],
) -> Callable[[_BaseExceptionT_co], bool]:
if isclass(condition) and issubclass(
cast(Type[BaseException], condition), BaseException
cast(Type[BaseException], condition), BaseException,
):
return partial(check_direct_subclass, parents=(condition,))
elif isinstance(condition, tuple):
if all(isclass(x) and issubclass(x, BaseException) for x in condition):
return partial(check_direct_subclass, parents=condition)
elif callable(condition):
return cast("Callable[[BaseException], bool]", condition)
return cast('Callable[[BaseException], bool]', condition)
raise TypeError("expected a function, exception type or tuple of exception types")
raise TypeError('expected a function, exception type or tuple of exception types')
class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
"""A combination of multiple unrelated exceptions."""
def __new__(
cls, __message: str, __exceptions: Sequence[_BaseExceptionT_co]
cls, __message: str, __exceptions: Sequence[_BaseExceptionT_co],
) -> Self:
if not isinstance(__message, str):
raise TypeError(f"argument 1 must be str, not {type(__message)}")
raise TypeError(f'argument 1 must be str, not {type(__message)}')
if not isinstance(__exceptions, Sequence):
raise TypeError("second argument (exceptions) must be a sequence")
raise TypeError('second argument (exceptions) must be a sequence')
if not __exceptions:
raise ValueError(
"second argument (exceptions) must be a non-empty sequence"
'second argument (exceptions) must be a non-empty sequence',
)
for i, exc in enumerate(__exceptions):
if not isinstance(exc, BaseException):
raise ValueError(
f"Item {i} of second argument (exceptions) is not an exception"
f'Item {i} of second argument (exceptions) is not an exception',
)
if cls is BaseExceptionGroup:
@ -72,11 +79,11 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
if not isinstance(exc, Exception):
if cls is ExceptionGroup:
raise TypeError(
"Cannot nest BaseExceptions in an ExceptionGroup"
'Cannot nest BaseExceptions in an ExceptionGroup',
)
else:
raise TypeError(
f"Cannot nest BaseExceptions in {cls.__name__!r}"
f'Cannot nest BaseExceptions in {cls.__name__!r}',
)
instance = super().__new__(cls, __message, __exceptions)
@ -87,10 +94,10 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
def add_note(self, note: str) -> None:
if not isinstance(note, str):
raise TypeError(
f"Expected a string, got note={note!r} (type {type(note).__name__})"
f'Expected a string, got note={note!r} (type {type(note).__name__})',
)
if not hasattr(self, "__notes__"):
if not hasattr(self, '__notes__'):
self.__notes__: list[str] = []
self.__notes__.append(note)
@ -107,27 +114,27 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
@overload
def subgroup(
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...]
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...],
) -> ExceptionGroup[_ExceptionT] | None:
...
@overload
def subgroup(
self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...]
self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...],
) -> BaseExceptionGroup[_BaseExceptionT] | None:
...
@overload
def subgroup(
self, __condition: Callable[[_BaseExceptionT_co | Self], bool]
self, __condition: Callable[[_BaseExceptionT_co | Self], bool],
) -> BaseExceptionGroup[_BaseExceptionT_co] | None:
...
def subgroup(
self,
__condition: type[_BaseExceptionT]
| tuple[type[_BaseExceptionT], ...]
| Callable[[_BaseExceptionT_co | Self], bool],
__condition: type[_BaseExceptionT] |
tuple[type[_BaseExceptionT], ...] |
Callable[[_BaseExceptionT_co | Self], bool],
) -> BaseExceptionGroup[_BaseExceptionT] | None:
condition = get_condition_filter(__condition)
modified = False
@ -161,7 +168,7 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
@overload
def split(
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...]
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...],
) -> tuple[
ExceptionGroup[_ExceptionT] | None,
BaseExceptionGroup[_BaseExceptionT_co] | None,
@ -170,7 +177,7 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
@overload
def split(
self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...]
self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...],
) -> tuple[
BaseExceptionGroup[_BaseExceptionT] | None,
BaseExceptionGroup[_BaseExceptionT_co] | None,
@ -179,7 +186,7 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
@overload
def split(
self, __condition: Callable[[_BaseExceptionT_co | Self], bool]
self, __condition: Callable[[_BaseExceptionT_co | Self], bool],
) -> tuple[
BaseExceptionGroup[_BaseExceptionT_co] | None,
BaseExceptionGroup[_BaseExceptionT_co] | None,
@ -188,19 +195,19 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
def split(
self,
__condition: type[_BaseExceptionT]
| tuple[type[_BaseExceptionT], ...]
| Callable[[_BaseExceptionT_co], bool],
__condition: type[_BaseExceptionT] |
tuple[type[_BaseExceptionT], ...] |
Callable[[_BaseExceptionT_co], bool],
) -> (
tuple[
ExceptionGroup[_ExceptionT] | None,
BaseExceptionGroup[_BaseExceptionT_co] | None,
]
| tuple[
] |
tuple[
BaseExceptionGroup[_BaseExceptionT] | None,
BaseExceptionGroup[_BaseExceptionT_co] | None,
]
| tuple[
] |
tuple[
BaseExceptionGroup[_BaseExceptionT_co] | None,
BaseExceptionGroup[_BaseExceptionT_co] | None,
]
@ -246,26 +253,26 @@ class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
@overload
def derive(
self, __excs: Sequence[_BaseExceptionT]
self, __excs: Sequence[_BaseExceptionT],
) -> BaseExceptionGroup[_BaseExceptionT]:
...
def derive(
self, __excs: Sequence[_BaseExceptionT]
self, __excs: Sequence[_BaseExceptionT],
) -> BaseExceptionGroup[_BaseExceptionT]:
eg = BaseExceptionGroup(self.message, __excs)
if hasattr(self, "__notes__"):
if hasattr(self, '__notes__'):
# Create a new list so that add_note() only affects one exceptiongroup
eg.__notes__ = list(self.__notes__)
return eg
def __str__(self) -> str:
suffix = "" if len(self._exceptions) == 1 else "s"
return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})"
suffix = '' if len(self._exceptions) == 1 else 's'
return f'{self.message} ({len(self._exceptions)} sub-exception{suffix})'
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})"
return f'{self.__class__.__name__}({self.message!r}, {self._exceptions!r})'
class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception):
@ -282,46 +289,46 @@ class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception):
@overload # type: ignore[override]
def subgroup(
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...]
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...],
) -> ExceptionGroup[_ExceptionT] | None:
...
@overload
def subgroup(
self, __condition: Callable[[_ExceptionT_co | Self], bool]
self, __condition: Callable[[_ExceptionT_co | Self], bool],
) -> ExceptionGroup[_ExceptionT_co] | None:
...
def subgroup(
self,
__condition: type[_ExceptionT]
| tuple[type[_ExceptionT], ...]
| Callable[[_ExceptionT_co], bool],
__condition: type[_ExceptionT] |
tuple[type[_ExceptionT], ...] |
Callable[[_ExceptionT_co], bool],
) -> ExceptionGroup[_ExceptionT] | None:
return super().subgroup(__condition)
@overload
def split(
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...]
self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...],
) -> tuple[
ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None
ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None,
]:
...
@overload
def split(
self, __condition: Callable[[_ExceptionT_co | Self], bool]
self, __condition: Callable[[_ExceptionT_co | Self], bool],
) -> tuple[
ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None
ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None,
]:
...
def split(
self: Self,
__condition: type[_ExceptionT]
| tuple[type[_ExceptionT], ...]
| Callable[[_ExceptionT_co], bool],
__condition: type[_ExceptionT] |
tuple[type[_ExceptionT], ...] |
Callable[[_ExceptionT_co], bool],
) -> tuple[
ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None
ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None,
]:
return super().split(__condition)

View file

@ -10,27 +10,29 @@ import textwrap
import traceback
from functools import singledispatch
from types import TracebackType
from typing import Any, List, Optional
from typing import Any
from typing import List
from typing import Optional
from ._exceptions import BaseExceptionGroup
max_group_width = 15
max_group_depth = 10
_cause_message = (
"\nThe above exception was the direct cause of the following exception:\n\n"
'\nThe above exception was the direct cause of the following exception:\n\n'
)
_context_message = (
"\nDuring handling of the above exception, another exception occurred:\n\n"
'\nDuring handling of the above exception, another exception occurred:\n\n'
)
def _format_final_exc_line(etype, value):
valuestr = _safe_string(value, "exception")
valuestr = _safe_string(value, 'exception')
if value is None or not valuestr:
line = f"{etype}\n"
line = f'{etype}\n'
else:
line = f"{etype}: {valuestr}\n"
line = f'{etype}: {valuestr}\n'
return line
@ -39,7 +41,7 @@ def _safe_string(value, what, func=str):
try:
return func(value)
except BaseException:
return f"<{what} {func.__name__}() failed>"
return f'<{what} {func.__name__}() failed>'
class _ExceptionPrintContext:
@ -49,14 +51,14 @@ class _ExceptionPrintContext:
self.need_close = False
def indent(self):
return " " * (2 * self.exception_group_depth)
return ' ' * (2 * self.exception_group_depth)
def emit(self, text_gen, margin_char=None):
if margin_char is None:
margin_char = "|"
margin_char = '|'
indent_str = self.indent()
if self.exception_group_depth:
indent_str += margin_char + " "
indent_str += margin_char + ' '
if isinstance(text_gen, str):
yield textwrap.indent(text_gen, indent_str, lambda line: True)
@ -66,9 +68,9 @@ class _ExceptionPrintContext:
def exceptiongroup_excepthook(
etype: type[BaseException], value: BaseException, tb: TracebackType | None
etype: type[BaseException], value: BaseException, tb: TracebackType | None,
) -> None:
sys.stderr.write("".join(traceback.format_exception(etype, value, tb)))
sys.stderr.write(''.join(traceback.format_exception(etype, value, tb)))
class PatchedTracebackException(traceback.TracebackException):
@ -86,7 +88,7 @@ class PatchedTracebackException(traceback.TracebackException):
) -> None:
kwargs: dict[str, Any] = {}
if sys.version_info >= (3, 10):
kwargs["compact"] = compact
kwargs['compact'] = compact
is_recursive_call = _seen is not None
if _seen is None:
@ -102,13 +104,13 @@ class PatchedTracebackException(traceback.TracebackException):
self.exc_type = exc_type
# Capture now to permit freeing resources: only complication is in the
# unofficial API _format_final_exc_line
self._str = _safe_string(exc_value, "exception")
self._str = _safe_string(exc_value, 'exception')
try:
self.__notes__ = getattr(exc_value, "__notes__", None)
self.__notes__ = getattr(exc_value, '__notes__', None)
except KeyError:
# Workaround for https://github.com/python/cpython/issues/98778 on Python
# <= 3.9, and some 3.10 and 3.11 patch versions.
HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ())
HTTPError = getattr(sys.modules.get('urllib.error', None), 'HTTPError', ())
if sys.version_info[:2] <= (3, 11) and isinstance(exc_value, HTTPError):
self.__notes__ = None
else:
@ -127,9 +129,9 @@ class PatchedTracebackException(traceback.TracebackException):
self.end_lineno = str(end_lno) if end_lno is not None else None
self.end_offset = exc_value.end_offset
elif (
exc_type
and issubclass(exc_type, (NameError, AttributeError))
and getattr(exc_value, "name", None) is not None
exc_type and
issubclass(exc_type, (NameError, AttributeError)) and
getattr(exc_value, 'name', None) is not None
):
suggestion = _compute_suggestion_error(exc_value, exc_traceback)
if suggestion:
@ -171,10 +173,10 @@ class PatchedTracebackException(traceback.TracebackException):
else:
need_context = True
if (
e
and e.__context__ is not None
and need_context
and id(e.__context__) not in _seen
e and
e.__context__ is not None and
need_context and
id(e.__context__) not in _seen
):
context = PatchedTracebackException(
type(e.__context__),
@ -243,12 +245,12 @@ class PatchedTracebackException(traceback.TracebackException):
yield from _ctx.emit(msg)
if exc.exceptions is None:
if exc.stack:
yield from _ctx.emit("Traceback (most recent call last):\n")
yield from _ctx.emit('Traceback (most recent call last):\n')
yield from _ctx.emit(exc.stack.format())
yield from _ctx.emit(exc.format_exception_only())
elif _ctx.exception_group_depth > max_group_depth:
# exception group, but depth exceeds limit
yield from _ctx.emit(f"... (max_group_depth is {max_group_depth})\n")
yield from _ctx.emit(f'... (max_group_depth is {max_group_depth})\n')
else:
# format exception group
is_toplevel = _ctx.exception_group_depth == 0
@ -257,8 +259,8 @@ class PatchedTracebackException(traceback.TracebackException):
if exc.stack:
yield from _ctx.emit(
"Exception Group Traceback (most recent call last):\n",
margin_char="+" if is_toplevel else None,
'Exception Group Traceback (most recent call last):\n',
margin_char='+' if is_toplevel else None,
)
yield from _ctx.emit(exc.stack.format())
@ -279,24 +281,24 @@ class PatchedTracebackException(traceback.TracebackException):
truncated = i >= max_group_width
else:
truncated = False
title = f"{i + 1}" if not truncated else "..."
title = f'{i + 1}' if not truncated else '...'
yield (
_ctx.indent()
+ ("+-" if i == 0 else " ")
+ f"+---------------- {title} ----------------\n"
_ctx.indent() +
('+-' if i == 0 else ' ') +
f'+---------------- {title} ----------------\n'
)
_ctx.exception_group_depth += 1
if not truncated:
yield from exc.exceptions[i].format(chain=chain, _ctx=_ctx)
else:
remaining = num_excs - max_group_width
plural = "s" if remaining > 1 else ""
plural = 's' if remaining > 1 else ''
yield from _ctx.emit(
f"and {remaining} more exception{plural}\n"
f'and {remaining} more exception{plural}\n',
)
if last_exc and _ctx.need_close:
yield _ctx.indent() + "+------------------------------------\n"
yield _ctx.indent() + '+------------------------------------\n'
_ctx.need_close = False
_ctx.exception_group_depth -= 1
@ -320,10 +322,10 @@ class PatchedTracebackException(traceback.TracebackException):
stype = self.exc_type.__qualname__
smod = self.exc_type.__module__
if smod not in ("__main__", "builtins"):
if smod not in ('__main__', 'builtins'):
if not isinstance(smod, str):
smod = "<unknown>"
stype = smod + "." + stype
smod = '<unknown>'
stype = smod + '.' + stype
if not issubclass(self.exc_type, SyntaxError):
yield _format_final_exc_line(stype, self._str)
@ -334,10 +336,10 @@ class PatchedTracebackException(traceback.TracebackException):
if isinstance(self.__notes__, collections.abc.Sequence):
for note in self.__notes__:
note = _safe_string(note, "note")
yield from [line + "\n" for line in note.split("\n")]
note = _safe_string(note, 'note')
yield from [line + '\n' for line in note.split('\n')]
elif self.__notes__ is not None:
yield _safe_string(self.__notes__, "__notes__", func=repr)
yield _safe_string(self.__notes__, '__notes__', func=repr)
traceback_exception_original_format = traceback.TracebackException.format
@ -345,7 +347,7 @@ traceback_exception_original_format_exception_only = (
traceback.TracebackException.format_exception_only
)
traceback_exception_format_syntax_error = getattr(
traceback.TracebackException, "_format_syntax_error", None
traceback.TracebackException, '_format_syntax_error', None,
)
if sys.excepthook is sys.__excepthook__:
traceback.TracebackException.__init__ = ( # type: ignore[assignment]
@ -371,10 +373,10 @@ if sys.excepthook is sys.__excepthook__:
# hook.
#
# More details: https://github.com/python-trio/trio/issues/1065
if getattr(sys.excepthook, "__name__", None) in (
"apport_excepthook",
if getattr(sys.excepthook, '__name__', None) in (
'apport_excepthook',
# on ubuntu 22.10 the hook was renamed to partial_apport_excepthook
"partial_apport_excepthook",
'partial_apport_excepthook',
):
# patch traceback like above
traceback.TracebackException.__init__ = ( # type: ignore[assignment]
@ -394,36 +396,36 @@ if getattr(sys.excepthook, "__name__", None) in (
assert sys.excepthook is apport_python_hook.apport_excepthook
# monkeypatch the sys module that apport has imported
fake_sys = ModuleType("exceptiongroup_fake_sys")
fake_sys = ModuleType('exceptiongroup_fake_sys')
fake_sys.__dict__.update(sys.__dict__)
fake_sys.__excepthook__ = exceptiongroup_excepthook
apport_python_hook.sys = fake_sys
@singledispatch
def format_exception_only(__exc: BaseException) -> List[str]:
def format_exception_only(__exc: BaseException) -> list[str]:
return list(
PatchedTracebackException(
type(__exc), __exc, None, compact=True
).format_exception_only()
type(__exc), __exc, None, compact=True,
).format_exception_only(),
)
@format_exception_only.register
def _(__exc: type, value: BaseException) -> List[str]:
def _(__exc: type, value: BaseException) -> list[str]:
return format_exception_only(value)
@singledispatch
def format_exception(
__exc: BaseException,
limit: Optional[int] = None,
limit: int | None = None,
chain: bool = True,
) -> List[str]:
) -> list[str]:
return list(
PatchedTracebackException(
type(__exc), __exc, __exc.__traceback__, limit=limit, compact=True
).format(chain=chain)
type(__exc), __exc, __exc.__traceback__, limit=limit, compact=True,
).format(chain=chain),
)
@ -432,16 +434,16 @@ def _(
__exc: type,
value: BaseException,
tb: TracebackType,
limit: Optional[int] = None,
limit: int | None = None,
chain: bool = True,
) -> List[str]:
) -> list[str]:
return format_exception(value, limit, chain)
@singledispatch
def print_exception(
__exc: BaseException,
limit: Optional[int] = None,
limit: int | None = None,
file: Any = None,
chain: bool = True,
) -> None:
@ -449,9 +451,9 @@ def print_exception(
file = sys.stderr
for line in PatchedTracebackException(
type(__exc), __exc, __exc.__traceback__, limit=limit
type(__exc), __exc, __exc.__traceback__, limit=limit,
).format(chain=chain):
print(line, file=file, end="")
print(line, file=file, end='')
@print_exception.register
@ -459,7 +461,7 @@ def _(
__exc: type,
value: BaseException,
tb: TracebackType,
limit: Optional[int] = None,
limit: int | None = None,
file: Any = None,
chain: bool = True,
) -> None:
@ -467,7 +469,7 @@ def _(
def print_exc(
limit: Optional[int] = None,
limit: int | None = None,
file: Any | None = None,
chain: bool = True,
) -> None:
@ -494,11 +496,11 @@ def _substitution_cost(ch_a, ch_b):
def _compute_suggestion_error(exc_value, tb):
wrong_name = getattr(exc_value, "name", None)
wrong_name = getattr(exc_value, 'name', None)
if wrong_name is None or not isinstance(wrong_name, str):
return None
if isinstance(exc_value, AttributeError):
obj = getattr(exc_value, "obj", _SENTINEL)
obj = getattr(exc_value, 'obj', _SENTINEL)
if obj is _SENTINEL:
return None
obj = exc_value.obj
@ -532,7 +534,7 @@ def _compute_suggestion_error(exc_value, tb):
# Don't take matches we've already beaten.
max_distance = min(max_distance, best_distance - 1)
current_distance = _levenshtein_distance(
wrong_name, possible_name, max_distance
wrong_name, possible_name, max_distance,
)
if current_distance > max_distance:
continue

View file

@ -1,3 +1,5 @@
from __future__ import annotations
import sys
from contextlib import AbstractContextManager

View file

@ -1,5 +1,6 @@
# file generated by setuptools_scm
# don't change, don't track in version control
from __future__ import annotations
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import Tuple, Union