[Python-checkins] bpo-40662: Fixed ast.get_source_segment for ast nodes that have incomplete location information (GH-20157)

Irit Katriel webhook-mailer at python.org
Mon May 18 14:14:20 EDT 2020


https://github.com/python/cpython/commit/e6578a226d8a8a13d1062d154fad0fef28ee2416
commit: e6578a226d8a8a13d1062d154fad0fef28ee2416
branch: master
author: Irit Katriel <iritkatriel at yahoo.com>
committer: GitHub <noreply at github.com>
date: 2020-05-18T19:14:12+01:00
summary:

bpo-40662: Fixed ast.get_source_segment for ast nodes that have incomplete location information (GH-20157)

Co-authored-by: Pablo Galindo <Pablogsal at gmail.com>

files:
A Misc/NEWS.d/next/Library/2020-05-18-12-56-45.bpo-40662.dfornR.rst
M Lib/ast.py
M Lib/test/test_ast.py

diff --git a/Lib/ast.py b/Lib/ast.py
index 61fbe030a7825..0d3b19d922368 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -332,6 +332,8 @@ def get_source_segment(source, node, *, padded=False):
     be padded with spaces to match its original position.
     """
     try:
+        if node.end_lineno is None or node.end_col_offset is None:
+            return None
         lineno = node.lineno - 1
         end_lineno = node.end_lineno - 1
         col_offset = node.col_offset
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 6b71adac4e4a6..e55d10badc37e 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -1851,6 +1851,17 @@ class C:
         cdef = ast.parse(s).body[0]
         self.assertEqual(ast.get_source_segment(s, cdef.body[0], padded=True), s_method)
 
+    def test_source_segment_missing_info(self):
+        s = 'v = 1\r\nw = 1\nx = 1\n\ry = 1\r\n'
+        v, w, x, y = ast.parse(s).body
+        del v.lineno
+        del w.end_lineno
+        del x.col_offset
+        del y.end_col_offset
+        self.assertIsNone(ast.get_source_segment(s, v))
+        self.assertIsNone(ast.get_source_segment(s, w))
+        self.assertIsNone(ast.get_source_segment(s, x))
+        self.assertIsNone(ast.get_source_segment(s, y))
 
 class NodeVisitorTests(unittest.TestCase):
     def test_old_constant_nodes(self):
diff --git a/Misc/NEWS.d/next/Library/2020-05-18-12-56-45.bpo-40662.dfornR.rst b/Misc/NEWS.d/next/Library/2020-05-18-12-56-45.bpo-40662.dfornR.rst
new file mode 100644
index 0000000000000..a960c3f61b6bb
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-05-18-12-56-45.bpo-40662.dfornR.rst
@@ -0,0 +1 @@
+Fixed :func:`ast.get_source_segment` for ast nodes that have incomplete location information. Patch by Irit Katriel.



More information about the Python-checkins mailing list