Skip to content

Commit 6cc31af

Browse files
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 200c9a8) Co-authored-by: Shantanu <[email protected]>
1 parent e13f49a commit 6cc31af

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
@@ -849,7 +849,7 @@ def visit_Import(self, node):
849849

850850
def visit_ImportFrom(self, node):
851851
self.fill("from ")
852-
self.write("." * node.level)
852+
self.write("." * (node.level or 0))
853853
if node.module:
854854
self.write(node.module)
855855
self.write(" import ")

Lib/test/test_unparse.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,12 @@ def test_invalid_fstring_backslash(self):
341341
def test_invalid_yield_from(self):
342342
self.check_invalid(ast.YieldFrom(value=None))
343343

344+
def test_import_from_level_none(self):
345+
tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')])
346+
self.assertEqual(ast.unparse(tree), "from mod import x")
347+
tree = ast.ImportFrom(module='mod', names=[ast.alias(name='x')], level=None)
348+
self.assertEqual(ast.unparse(tree), "from mod import x")
349+
344350
def test_docstrings(self):
345351
docstrings = (
346352
'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)