Skip to content

Commit 7d98c4e

Browse files
temyurchenkogithub-actions[bot]
authored andcommitted
change the type annotation error heuristic (#2583)
The previous one depended on the message from "typed_ast", which is not used anymore. Instead, we check if there is a "# type:" substring in the source line of the exception. This can yield some false positives, but probably rarely. (cherry picked from commit 62c5bad)
1 parent 6042e58 commit 7d98c4e

File tree

3 files changed

+10
-10
lines changed

3 files changed

+10
-10
lines changed

astroid/builder.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
import ast
1414
import os
15+
import re
1516
import textwrap
1617
import types
1718
import warnings
@@ -33,7 +34,6 @@
3334
# The comment used to select a statement to be extracted
3435
# when calling extract_node.
3536
_STATEMENT_SELECTOR = "#@"
36-
MISPLACED_TYPE_ANNOTATION_ERROR = "misplaced type annotation"
3737

3838
if PY312_PLUS:
3939
warnings.filterwarnings("ignore", "invalid escape sequence", SyntaxWarning)
@@ -479,9 +479,11 @@ def _parse_string(
479479
)
480480
except SyntaxError as exc:
481481
# If the type annotations are misplaced for some reason, we do not want
482-
# to fail the entire parsing of the file, so we need to retry the parsing without
483-
# type comment support.
484-
if exc.args[0] != MISPLACED_TYPE_ANNOTATION_ERROR or not type_comments:
482+
# to fail the entire parsing of the file, so we need to retry the
483+
# parsing without type comment support. We use a heuristic for
484+
# determining if the error is due to type annotations.
485+
type_annot_related = re.search(r"#\s+type:", exc.text or "")
486+
if not (type_annot_related and type_comments):
485487
raise
486488

487489
parser_module = get_parser_module(type_comments=False)

tests/test_builder.py

-6
Original file line numberDiff line numberDiff line change
@@ -914,12 +914,6 @@ def test_module_build_dunder_file() -> None:
914914
assert module.path[0] == collections.__file__
915915

916916

917-
@pytest.mark.xfail(
918-
reason=(
919-
"The builtin ast module does not fail with a specific error "
920-
"for syntax error caused by invalid type comments."
921-
),
922-
)
923917
def test_parse_module_with_invalid_type_comments_does_not_crash():
924918
node = builder.parse(
925919
"""

tests/test_nodes.py

+4
Original file line numberDiff line numberDiff line change
@@ -1304,6 +1304,10 @@ def test_type_comments_invalid_expression() -> None:
13041304
def test_type_comments_invalid_function_comments() -> None:
13051305
module = builder.parse(
13061306
"""
1307+
def func(
1308+
# type: () -> int # inside parentheses
1309+
):
1310+
pass
13071311
def func():
13081312
# type: something completely invalid
13091313
pass

0 commit comments

Comments
 (0)