[Python-checkins] gh-92986: Fix ast.unparse when ImportFrom.level is None (GH-92992)

miss-islington webhook-mailer at python.org
Mon Sep 5 13:39:58 EDT 2022


https://github.com/python/cpython/commit/6cc31af657a0aaf5a8ba0564b35124f1ca542287
commit: 6cc31af657a0aaf5a8ba0564b35124f1ca542287
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2022-09-05T10:39:52-07:00
summary:

gh-92986: Fix ast.unparse when ImportFrom.level is None (GH-92992)


This doesn't happen naturally, but is allowed by the ASDL and compiler.
We don't want to change ASDL for backward compatibility reasons
(GH-57645, GH-92987)
(cherry picked from commit 200c9a8da0e2b892c476807e986009c01327e781)

Co-authored-by: Shantanu <12621235+hauntsaninja at users.noreply.github.com>

files:
A Misc/NEWS.d/next/Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst
M Lib/ast.py
M Lib/test/test_unparse.py

diff --git a/Lib/ast.py b/Lib/ast.py
index f4d2f6e42c0..d63cb2fe80f 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -849,7 +849,7 @@ def visit_Import(self, node):
 
     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 ")
diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py
index 33e1149bfd3..6e38c5e8468 100644
--- a/Lib/test/test_unparse.py
+++ b/Lib/test/test_unparse.py
@@ -341,6 +341,12 @@ def test_invalid_fstring_backslash(self):
     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
index 00000000000..691c0dd3759
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst
@@ -0,0 +1 @@
+Fix :func:`ast.unparse` when ``ImportFrom.level`` is None



More information about the Python-checkins mailing list