Skip to content

Commit 38766d9

Browse files
hauntsaninjaisidentical
authored andcommitted
[3.11] pythongh-92986: Fix ast.unparse when ImportFrom.level is None (pythonGH-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 (pythonGH-57645, pythonGH-92987) (cherry picked from commit 200c9a8) Co-authored-by: Shantanu <[email protected]>
1 parent d09069a commit 38766d9

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

853853
def visit_ImportFrom(self, node):
854854
self.fill("from ")
855-
self.write("." * node.level)
855+
self.write("." * (node.level or 0))
856856
if node.module:
857857
self.write(node.module)
858858
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)