]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-92986: Fix ast.unparse when ImportFrom.level is None (#92992)
authorShantanu <12621235+hauntsaninja@users.noreply.github.com>
Mon, 5 Sep 2022 17:14:50 +0000 (10:14 -0700)
committerGitHub <noreply@github.com>
Mon, 5 Sep 2022 17:14:50 +0000 (20:14 +0300)
This doesn't happen naturally, but is allowed by the ASDL and compiler.
We don't want to change ASDL for backward compatibility reasons
(#57645, #92987)

Lib/ast.py
Lib/test/test_unparse.py
Misc/NEWS.d/next/Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst [new file with mode: 0644]

index 8af6d1ed14db77536468748986250dc6ca3665f9..8adb61fed45388430bfa3a03000f667ee4338861 100644 (file)
@@ -853,7 +853,7 @@ class _Unparser(NodeVisitor):
 
     def visit_ImportFrom(self, node):
         self.fill("from ")
-        self.write("." * node.level)
+        self.write("." * (node.level or 0))
         if node.module:
             self.write(node.module)
         self.write(" import ")
index 969aa16678f493552789d9c6f64ca6c3f2824ed2..f1f1dd5dc26be8473e6b2d27340b0bab4a32ff6c 100644 (file)
@@ -422,6 +422,12 @@ class UnparseTestCase(ASTTestCase):
     def test_invalid_yield_from(self):
         self.check_invalid(ast.YieldFrom(value=None))
 
+    def test_import_from_level_none(self):
+        tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')])
+        self.assertEqual(ast.unparse(tree), "from mod import x")
+        tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')], level=None)
+        self.assertEqual(ast.unparse(tree), "from mod import x")
+
     def test_docstrings(self):
         docstrings = (
             'this ends with double quote"',
diff --git a/Misc/NEWS.d/next/Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst b/Misc/NEWS.d/next/Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst
new file mode 100644 (file)
index 0000000..691c0dd
--- /dev/null
@@ -0,0 +1 @@
+Fix :func:`ast.unparse` when ``ImportFrom.level`` is None