diff --git a/python/py_helpers.py b/python/py_helpers.py index 278b6f7..6fce2b1 100644 --- a/python/py_helpers.py +++ b/python/py_helpers.py @@ -436,6 +436,20 @@ def _find_conditions(tree): return [Node(test) for test in _find_conditions(self.tree)] + # Returs a Boolean indicating if node1 comes before node2 + def is_ordered(self, node1, node2): + if not self._has_body(): + return False + first, second = None, None + for index, node in enumerate(self.tree.body): + if Node(node).is_equivalent(node1): + first = index + elif Node(node).is_equivalent(node2): + second = index + if first is not None and second is not None: + return first < second + return False + # Exception formatting functions. Currently bundled with the Node class, until # we improve the testing, building and CI so that they can easily handle diff --git a/python/py_helpers.test.py b/python/py_helpers.test.py index abefee8..6a9fbbd 100644 --- a/python/py_helpers.test.py +++ b/python/py_helpers.test.py @@ -1343,6 +1343,24 @@ def foo(spam): class TestGenericHelpers(unittest.TestCase): + def test_is_ordered(self): + code_str = """ +x = 1 +if x: + print("x is:") + print(x) +x = 0 +""" + self.assertTrue(Node(code_str).is_ordered("x=1", "x=0")) + self.assertTrue( + Node(code_str).find_ifs()[0].is_ordered("print('x is:')", "print(x)") + ) + self.assertFalse(Node(code_str).is_ordered("x=0", "x=1")) + self.assertFalse( + Node(code_str).find_ifs()[0].is_ordered("print(x)", "print('x is:')") + ) + self.assertFalse(Node(code_str).is_ordered("x=2", "x=0")) + def test_has_stmt(self): self.assertTrue( Node("name = input('hi')\nself.matrix[1][5] = 3").has_stmt(