Skip to content

Commit 6ff59a2

Browse files
committed
improved exception error message for syntax errors in fstrings
1 parent 6295428 commit 6ff59a2

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

custom_components/pyscript/eval.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1872,7 +1872,10 @@ def parse(self, code_str, filename=None, mode="exec"):
18721872
self.lineno = err.lineno
18731873
self.col_offset = err.offset - 1
18741874
self.exception = f"syntax error {err}"
1875-
self.exception_long = self.format_exc(err, self.lineno, self.col_offset)
1875+
if err.filename == self.filename:
1876+
self.exception_long = self.format_exc(err, self.lineno, self.col_offset)
1877+
else:
1878+
self.exception_long = self.format_exc(err, 1, self.col_offset, code_list=[err.text])
18761879
return False
18771880
except asyncio.CancelledError:
18781881
raise
@@ -1884,15 +1887,17 @@ def parse(self, code_str, filename=None, mode="exec"):
18841887
self.exception_long = self.format_exc(err)
18851888
return False
18861889

1887-
def format_exc(self, exc, lineno=None, col_offset=None, short=False):
1890+
def format_exc(self, exc, lineno=None, col_offset=None, short=False, code_list=None):
18881891
"""Format an multi-line exception message using lineno if available."""
1892+
if code_list is None:
1893+
code_list = self.code_list
18891894
if lineno is not None:
18901895
if short:
18911896
mesg = f"In <{self.filename}> line {lineno}:\n"
1892-
mesg += " " + self.code_list[lineno - 1]
1897+
mesg += " " + code_list[lineno - 1]
18931898
else:
18941899
mesg = f"Exception in <{self.filename}> line {lineno}:\n"
1895-
mesg += " " + self.code_list[lineno - 1] + "\n"
1900+
mesg += " " + code_list[lineno - 1] + "\n"
18961901
if col_offset is not None:
18971902
mesg += " " + " " * col_offset + "^\n"
18981903
mesg += f"{type(exc).__name__}: {exc}"

tests/test_unit_eval.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,8 @@ async def test_eval(hass):
919919
"import math; math.sinXYZ",
920920
"Exception in test line 1 column 13: module 'math' has no attribute 'sinXYZ'",
921921
],
922+
["f'xxx{'", "syntax error f-string: expecting '}' (test, line 1)"],
923+
["f'xxx{foo() i}'", "syntax error invalid syntax (<fstring>, line 1)"],
922924
["del xx", "Exception in test line 1 column 0: name 'xx' is not defined"],
923925
["return", "Exception in test line 1 column 0: return statement outside function"],
924926
["break", "Exception in test line 1 column 0: break statement outside loop"],

0 commit comments

Comments
 (0)