From 200c9a8da0e2b892c476807e986009c01327e781 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 5 Sep 2022 10:14:50 -0700 Subject: [PATCH] gh-92986: Fix ast.unparse when ImportFrom.level is None (#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 (#57645, #92987) --- Lib/ast.py | 2 +- Lib/test/test_unparse.py | 6 ++++++ .../Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2022-05-19-22-34-42.gh-issue-92986.e6uKxj.rst diff --git a/Lib/ast.py b/Lib/ast.py index 8af6d1ed14d..8adb61fed45 100644 --- a/Lib/ast.py +++ b/Lib/ast.py @@ -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 ") diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py index 969aa16678f..f1f1dd5dc26 100644 --- a/Lib/test/test_unparse.py +++ b/Lib/test/test_unparse.py @@ -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 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