Skip to content

Commit a0848d1

Browse files
[3.11] gh-92986: Fix ast.unparse when ImportFrom.level is None (GH-92992) (GH-96593)
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]> Co-authored-by: Shantanu <[email protected]>
1 parent 08d8058 commit a0848d1

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

Lib/ast.py

+1-1
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

+6
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"',
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)