[Python-checkins] r62092 - in sandbox/trunk/2to3/lib2to3: pytree.py tests/test_pytree.py

collin.winter python-checkins at python.org
Tue Apr 1 18:27:10 CEST 2008


Author: collin.winter
Date: Tue Apr  1 18:27:10 2008
New Revision: 62092

Modified:
   sandbox/trunk/2to3/lib2to3/pytree.py
   sandbox/trunk/2to3/lib2to3/tests/test_pytree.py
Log:
Add get_prev_sibling() to complement pytree's get_next_sibling().

Modified: sandbox/trunk/2to3/lib2to3/pytree.py
==============================================================================
--- sandbox/trunk/2to3/lib2to3/pytree.py	(original)
+++ sandbox/trunk/2to3/lib2to3/pytree.py	Tue Apr  1 18:27:10 2008
@@ -167,13 +167,27 @@
             return None
 
         # Can't use index(); we need to test by identity
-        for i, sibling in enumerate(self.parent.children):
-            if sibling is self:
+        for i, child in enumerate(self.parent.children):
+            if child is self:
                 try:
                     return self.parent.children[i+1]
                 except IndexError:
                     return None
 
+    def get_prev_sibling(self):
+        """Return the node immediately preceding the invocant in their
+        parent's children list. If the invocant does not have a previous
+        sibling, return None."""
+        if self.parent is None:
+            return None
+
+        # Can't use index(); we need to test by identity
+        for i, child in enumerate(self.parent.children):
+            if child is self:
+                if i == 0:
+                    return None
+                return self.parent.children[i-1]
+
     def get_suffix(self):
         """Return the string immediately following the invocant node. This
         is effectively equivalent to node.get_next_sibling().get_prefix()"""

Modified: sandbox/trunk/2to3/lib2to3/tests/test_pytree.py
==============================================================================
--- sandbox/trunk/2to3/lib2to3/tests/test_pytree.py	(original)
+++ sandbox/trunk/2to3/lib2to3/tests/test_pytree.py	Tue Apr  1 18:27:10 2008
@@ -319,6 +319,24 @@
         self.assertEqual(l2.get_next_sibling(), None)
         self.assertEqual(p1.get_next_sibling(), None)
 
+    def testNodePrevSibling(self):
+        n1 = pytree.Node(1000, [])
+        n2 = pytree.Node(1000, [])
+        p1 = pytree.Node(1000, [n1, n2])
+
+        self.failUnless(n2.get_prev_sibling() is n1)
+        self.assertEqual(n1.get_prev_sibling(), None)
+        self.assertEqual(p1.get_prev_sibling(), None)
+
+    def testLeafPrevSibling(self):
+        l1 = pytree.Leaf(100, "a")
+        l2 = pytree.Leaf(100, "b")
+        p1 = pytree.Node(1000, [l1, l2])
+
+        self.failUnless(l2.get_prev_sibling() is l1)
+        self.assertEqual(l1.get_prev_sibling(), None)
+        self.assertEqual(p1.get_prev_sibling(), None)
+
 
 class TestPatterns(support.TestCase):
 


More information about the Python-checkins mailing list