Skip to content

Commit 280191c

Browse files
committed
New approach
1 parent 885ea01 commit 280191c

File tree

2 files changed

+26
-19
lines changed

2 files changed

+26
-19
lines changed

astroid/rebuilder.py

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,25 +1389,16 @@ def _find_orelse_keyword(
13891389
if not self._data or not node.orelse:
13901390
return None, None
13911391

1392-
end_lineno = node.orelse[0].lineno
1393-
1394-
def find_keyword(begin: int, end: int) -> Tuple[Optional[int], Optional[int]]:
1395-
# pylint: disable-next=unsubscriptable-object
1396-
data = "\n".join(self._data[begin:end])
1397-
1398-
try:
1399-
tokens = list(generate_tokens(StringIO(data).readline))
1400-
except tokenize.TokenError:
1401-
# If we cut-off in the middle of multi-line if statements we
1402-
# generate a TokenError here. We just keep trying
1403-
# until the multi-line statement is closed.
1404-
return find_keyword(begin, end + 1)
1405-
for t in tokens[::-1]:
1406-
if t.type == token.NAME and t.string in {"else", "elif"}:
1407-
return node.lineno + t.start[0] - 1, t.start[1]
1408-
raise AssertionError() # pragma: no cover # Shouldn't be reached.
1409-
1410-
return find_keyword(node.lineno - 1, end_lineno)
1392+
start = node.orelse[0].lineno
1393+
1394+
# pylint: disable-next=unsubscriptable-object
1395+
for index, line in enumerate(self._data[start::-1]):
1396+
if line.rstrip().startswith("else"):
1397+
return start - index + 1, line.index("else")
1398+
if line.rstrip().startswith("elif"):
1399+
return start - index + 1, line.index("elif")
1400+
1401+
return None, None
14111402

14121403
def visit_if(self, node: "ast.If", parent: NodeNG) -> nodes.If:
14131404
"""visit an If node by returning a fresh instance of it"""

tests/unittest_nodes.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,18 @@ class IfNodeTest(_NodeTest):
322322
pass
323323
else:
324324
raise
325+
326+
if 1:
327+
print()
328+
elif (
329+
2
330+
and 3
331+
):
332+
print()
333+
else:
334+
# This is using else in a comment
335+
raise
336+
325337
"""
326338

327339
def test_if_elif_else_node(self) -> None:
@@ -357,6 +369,10 @@ def test_orelse_line_numbering(self) -> None:
357369
assert self.astroid.body[3].orelse[0].orelse_col_offset == 0
358370
assert self.astroid.body[3].orelse[0].orelse[0].orelse_lineno == 21
359371
assert self.astroid.body[3].orelse[0].orelse[0].orelse_col_offset == 0
372+
assert self.astroid.body[4].orelse_lineno == 26
373+
assert self.astroid.body[4].orelse_col_offset == 0
374+
assert self.astroid.body[4].orelse[0].orelse_lineno == 31
375+
assert self.astroid.body[4].orelse[0].orelse_col_offset == 0
360376

361377
@staticmethod
362378
@pytest.mark.filterwarnings("ignore:.*is_sys_guard:DeprecationWarning")

0 commit comments

Comments
 (0)