Skip to content

Commit 729b252

Browse files
authored
gh-104741: Add line number attribute to indentation error exception (#104743)
1 parent 0a77960 commit 729b252

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

Lib/test/test_tabnanny.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ def test_with_errored_file(self):
317317
with TemporaryPyFile(SOURCE_CODES["wrong_indented"]) as file_path:
318318
stderr = f"{file_path!r}: Token Error: "
319319
stderr += ('unindent does not match any outer indentation level'
320-
' (<tokenize>, line 3)')
320+
' (<string>, line 3)')
321321
self.validate_cmd(file_path, stderr=stderr, expect_failure=True)
322322

323323
def test_with_error_free_file(self):

Lib/test/test_tokenize.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,18 @@ def k(x):
9292
readline = BytesIO(indent_error_file).readline
9393
with self.assertRaisesRegex(IndentationError,
9494
"unindent does not match any "
95-
"outer indentation level"):
95+
"outer indentation level") as e:
9696
for tok in tokenize(readline):
9797
pass
98+
self.assertEqual(e.exception.lineno, 3)
99+
self.assertEqual(e.exception.filename, '<string>')
100+
self.assertEqual(e.exception.end_lineno, None)
101+
self.assertEqual(e.exception.end_offset, None)
102+
self.assertEqual(
103+
e.exception.msg,
104+
'unindent does not match any outer indentation level')
105+
self.assertEqual(e.exception.offset, 9)
106+
self.assertEqual(e.exception.text, ' x += 5\n')
98107

99108
def test_int(self):
100109
# Ordinary integers and binary operators

Python/Python-tokenize.c

+9-6
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,9 @@ _tokenizer_error(struct tok_state *tok)
8989
}
9090
return -1;
9191
case E_DEDENT:
92-
PyErr_Format(PyExc_IndentationError,
93-
"unindent does not match any outer indentation level "
94-
"(<tokenize>, line %d)",
95-
tok->lineno);
96-
return -1;
92+
msg = "unindent does not match any outer indentation level";
93+
errtype = PyExc_IndentationError;
94+
break;
9795
case E_INTR:
9896
if (!PyErr_Occurred()) {
9997
PyErr_SetNone(PyExc_KeyboardInterrupt);
@@ -131,7 +129,12 @@ _tokenizer_error(struct tok_state *tok)
131129
goto exit;
132130
}
133131

134-
tmp = Py_BuildValue("(OnnOii)", tok->filename, tok->lineno, 0, error_line, 0, 0);
132+
Py_ssize_t offset = _PyPegen_byte_offset_to_character_offset(error_line, tok->inp - tok->buf);
133+
if (offset == -1) {
134+
result = -1;
135+
goto exit;
136+
}
137+
tmp = Py_BuildValue("(OnnOOO)", tok->filename, tok->lineno, offset, error_line, Py_None, Py_None);
135138
if (!tmp) {
136139
result = -1;
137140
goto exit;

0 commit comments

Comments
 (0)