Skip to content

Commit 200c9a8

Browse files
authored
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)
1 parent 2c7d2e8 commit 200c9a8

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

Lib/ast.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -853,7 +853,7 @@ def visit_Import(self, node):
853853

854854
def visit_ImportFrom(self, node):
855855
self.fill("from ")
856-
self.write("." * node.level)
856+
self.write("." * (node.level or 0))
857857
if node.module:
858858
self.write(node.module)
859859
self.write(" import ")

Lib/test/test_unparse.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,12 @@ def test_invalid_fstring_backslash(self):
422422
def test_invalid_yield_from(self):
423423
self.check_invalid(ast.YieldFrom(value=None))
424424

425+
def test_import_from_level_none(self):
426+
tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')])
427+
self.assertEqual(ast.unparse(tree), "from mod import x")
428+
tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')], level=None)
429+
self.assertEqual(ast.unparse(tree), "from mod import x")
430+
425431
def test_docstrings(self):
426432
docstrings = (
427433
'this ends with double quote"',
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`ast.unparse` when ``ImportFrom.level`` is None

0 commit comments

Comments
 (0)