Skip to content

Commit

Permalink
Completes type hints for exc and utils modules
Browse files Browse the repository at this point in the history
  • Loading branch information
Daverball committed Jan 3, 2024
1 parent 103c64b commit 219cbdf
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 65 deletions.
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ exclude = "/tests/"
follow_imports = "silent"

[[tool.mypy.overrides]]
# strict config for public API
# strict config for fully typed modules and public API
module = [
"chameleon.exc.RenderError",
"chameleon.exc.TemplateError",
"chameleon.exc.*",
"chameleon.utils.*",
"chameleon.zpt.loader.*",
"chameleon.zpt.template.*",
]
Expand Down
52 changes: 38 additions & 14 deletions src/chameleon/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import traceback
from typing import TYPE_CHECKING
from typing import Any

from chameleon.config import SOURCE_EXPRESSION_MARKER_LENGTH as LENGTH
from chameleon.tokenize import Token
Expand All @@ -10,10 +11,19 @@


if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Iterable
from collections.abc import Iterator
from collections.abc import Mapping
from typing_extensions import Self


def compute_source_marker(line, column, expression, size):
def compute_source_marker(
line: str,
column: int,
expression: str,
size: int
) -> tuple[str, str]:
"""Computes source marker location string.
>>> def test(l, c, e, s):
Expand Down Expand Up @@ -76,9 +86,9 @@ def compute_source_marker(line, column, expression, size):
size = len(expression)
else:
window = (size - len(expression)) / 2.0
offset = column - window
offset -= min(3, max(0, column + window + len(expression) - len(s)))
offset = int(offset)
f_offset = column - window
f_offset -= min(3, max(0, column + window + len(expression) - len(s)))
offset = int(f_offset)

if offset > 0:
s = s[offset:]
Expand All @@ -97,7 +107,13 @@ def compute_source_marker(line, column, expression, size):
return s, column * " " + marker


def iter_source_marker_lines(source, expression, line, column):
def iter_source_marker_lines(
source: Iterable[str],
expression: str,
line: int,
column: int
) -> Iterator[str]:

for i, l in enumerate(source):
if i + 1 != line:
continue
Expand All @@ -111,7 +127,7 @@ def iter_source_marker_lines(source, expression, line, column):
break


def ellipsify(string, limit):
def ellipsify(string: str, limit: int) -> str:
if len(string) > limit:
return "... " + string[-(limit - 4):]

Expand Down Expand Up @@ -172,6 +188,7 @@ def __str__(self) -> str:
text += "\n"
text += " - Location: (line %d: col %d)" % (lineno, column)

lines: Iterable[str]
if lineno and column:
if self.token.source:
lines = iter_source_marker_lines(
Expand All @@ -184,7 +201,7 @@ def __str__(self) -> str:
except OSError:
pass
else:
iter_source_marker_lines(
lines = iter_source_marker_lines(
iter(f), self.token, lineno, column
)
try:
Expand Down Expand Up @@ -262,7 +279,14 @@ class ExpressionError(LanguageError):


class ExceptionFormatter:
def __init__(self, errors, econtext, rcontext, value_repr) -> None:
def __init__(
self,
errors: list[tuple[str, int, int, str, BaseException]],
econtext: Mapping[str, object],
rcontext: dict[str, Any],
value_repr: Callable[[object], str]
) -> None:

kwargs = rcontext.copy()
kwargs.update(econtext)

Expand All @@ -274,16 +298,16 @@ def __init__(self, errors, econtext, rcontext, value_repr) -> None:
self._kwargs = kwargs
self._value_repr = value_repr

def __call__(self):
def __call__(self) -> str:
# Format keyword arguments; consecutive arguments are indented
# for readability
formatted = [
formatted_args = [
"{}: {}".format(name, self._value_repr(value))
for name, value in self._kwargs.items()
]

for index, string in enumerate(formatted[1:]):
formatted[index + 1] = " " * 15 + string
for index, string in enumerate(formatted_args[1:]):
formatted_args[index + 1] = " " * 15 + string

out = []

Expand Down Expand Up @@ -319,14 +343,14 @@ def __call__(self):
finally:
f.close()

out.append(" - Arguments: %s" % "\n".join(formatted))
out.append(" - Arguments: %s" % "\n".join(formatted_args))

if isinstance(exc.__str__, ExceptionFormatter):
# This is a nested error that has already been wrapped
# We must unwrap it before trying to format it to prevent
# recursion
exc = create_formatted_exception(
exc, type(exc), exc._original__str__)
exc, type(exc), exc._original__str__) # type: ignore
formatted = traceback.format_exception_only(type(exc), exc)[-1]
formatted_class = "%s:" % type(exc).__name__

Expand Down
2 changes: 1 addition & 1 deletion src/chameleon/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def render(self, **__kw: Any) -> str:

try:
exc = create_formatted_exception(
exc, cls, formatter, RenderError
exc, cls, formatter, RenderError # type: ignore
)
except TypeError:
pass
Expand Down
Loading

0 comments on commit 219cbdf

Please sign in to comment.