Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update line number handling and provide better traceback. #14

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 35 additions & 9 deletions localscope/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import functools as ft
import inspect
import logging
import textwrap
import types
from typing import Any, Callable, Dict, Iterable, Optional, Set, Union

Expand Down Expand Up @@ -117,14 +118,36 @@ def __init__(
self,
message: str,
code: types.CodeType,
instruction: Optional[dis.Instruction] = None,
instruction: dis.Instruction,
lineno: Optional[int] = None,
) -> None:
if instruction and instruction.starts_line:
lineno = instruction.starts_line
else:
lineno = code.co_firstlineno
details = f'file "{code.co_filename}", line {lineno}, in {code.co_name}'
super().__init__(f"{message} ({details})")
source = None
lineno = instruction.starts_line if lineno is None else lineno
if lineno is not None:
# Add the source code if we can find it.
try:
# Get the source, dedent, re-indent, and add a marker where the
# error occurred.
lines, start = inspect.getsourcelines(code)
lines = textwrap.dedent("".join(lines)).split("\n")
text = "\n".join(
f"{no:3}: {line}" for no, line in enumerate(lines, start=start)
)
lines = textwrap.indent(text, " ").split("\n")
offset = lineno - start
lines[offset] = "--> " + lines[offset][4:]

# Don't show all lines of the source.
lines = lines[max(0, offset - 2) : offset + 3]
source = "\n".join(lines)
except OSError: # pragma: no cover
pass
message = (
f'{message} (file "{code.co_filename}", line {lineno}, in {code.co_name})'
)
if source:
message = f"{message}\n{source}"
super().__init__(message)


def _localscope(
Expand Down Expand Up @@ -162,8 +185,11 @@ def _localscope(
forbidden_opnames.add("LOAD_DEREF")

LOGGER.info("analysing instructions for %s...", func)
lineno = None
for instruction in dis.get_instructions(code):
LOGGER.info(instruction)
if instruction.starts_line is not None:
lineno = instruction.starts_line
name = instruction.argval
if instruction.opname in forbidden_opnames:
# Variable explicitly allowed by name or in `builtins`.
Expand All @@ -172,13 +198,13 @@ def _localscope(
# Complain if the variable is not available.
if name not in _globals:
raise LocalscopeException(
f"`{name}` is not in globals", code, instruction
f"`{name}` is not in globals", code, instruction, lineno
)
# Check if variable is allowed by value.
value = _globals[name]
if not predicate(value):
raise LocalscopeException(
f"`{name}` is not a permitted global", code, instruction
f"`{name}` is not a permitted global", code, instruction, lineno
)
elif instruction.opname == "STORE_DEREF":
# Store a new allowed variable which has been created in the scope of the
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "localscope"
version = "0.2.1"
version = "0.2.2"
requires-python = ">=3.8"
authors = [
{name = "Till Hoffmann"},
Expand Down
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
[flake8]
max-line-length = 88
ignore = E203
exclude =
playground
venv

[tool:pytest]
Expand Down
24 changes: 24 additions & 0 deletions tests/test_localscope.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,27 @@ class MyOtherClass:
@localscope(allowed=["x"])
def my_func(self, a):
return a + x


def test_source():
x = 1

def foo():
# This
# is
# a
# long
# source
# file.
if True:
print(x)

# We
# have
# printed
# something
# here.

with pytest.raises(LocalscopeException) as raised:
localscope(foo)
assert "--> 240: print(x)" in str(raised.value)