File tree Expand file tree Collapse file tree 3 files changed +10
-10
lines changed Expand file tree Collapse file tree 3 files changed +10
-10
lines changed Original file line number Diff line number Diff line change 1212
1313import ast
1414import os
15+ import re
1516import textwrap
1617import types
1718import warnings
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
3838if PY312_PLUS :
3939 warnings .filterwarnings ("ignore" , "invalid escape sequence" , SyntaxWarning )
@@ -478,9 +478,11 @@ def _parse_string(
478478 )
479479 except SyntaxError as exc :
480480 # If the type annotations are misplaced for some reason, we do not want
481- # to fail the entire parsing of the file, so we need to retry the parsing without
482- # type comment support.
483- if exc .args [0 ] != MISPLACED_TYPE_ANNOTATION_ERROR or not type_comments :
481+ # to fail the entire parsing of the file, so we need to retry the
482+ # parsing without type comment support. We use a heuristic for
483+ # determining if the error is due to type annotations.
484+ type_annot_related = re .search (r"#\s+type:" , exc .text or "" )
485+ if not (type_annot_related and type_comments ):
484486 raise
485487
486488 parser_module = get_parser_module (type_comments = False )
Original file line number Diff line number Diff line change @@ -883,12 +883,6 @@ def test_module_build_dunder_file() -> None:
883883 assert module .path [0 ] == collections .__file__
884884
885885
886- @pytest .mark .xfail (
887- reason = (
888- "The builtin ast module does not fail with a specific error "
889- "for syntax error caused by invalid type comments."
890- ),
891- )
892886def test_parse_module_with_invalid_type_comments_does_not_crash ():
893887 node = builder .parse (
894888 """
Original file line number Diff line number Diff line change @@ -1304,6 +1304,10 @@ def test_type_comments_invalid_expression() -> None:
13041304def 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
You can’t perform that action at this time.
0 commit comments