From aef92aee0f0473e3dbee38566e790edc47cba926 Mon Sep 17 00:00:00 2001 From: Casey Brooks Date: Fri, 26 Dec 2025 19:15:42 +0000 Subject: [PATCH] fix(pycode): preserve single-tuple comma --- sphinx/pycode/ast.py | 9 ++++++--- tests/test_pycode_ast.py | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py index f541ec0a90c..17b34da33b9 100644 --- a/sphinx/pycode/ast.py +++ b/sphinx/pycode/ast.py @@ -213,11 +213,14 @@ def visit_UnaryOp(self, node: ast.UnaryOp) -> str: return "%s %s" % (self.visit(node.op), self.visit(node.operand)) def visit_Tuple(self, node: ast.Tuple) -> str: - if node.elts: - return "(" + ", ".join(self.visit(e) for e in node.elts) + ")" - else: + if not node.elts: return "()" + if len(node.elts) == 1: + return "(%s,)" % self.visit(node.elts[0]) + + return "(" + ", ".join(self.visit(e) for e in node.elts) + ")" + if sys.version_info < (3, 8): # these ast nodes were deprecated in python 3.8 def visit_Bytes(self, node: ast.Bytes) -> str: diff --git a/tests/test_pycode_ast.py b/tests/test_pycode_ast.py index e8006235172..214fee3dd8c 100644 --- a/tests/test_pycode_ast.py +++ b/tests/test_pycode_ast.py @@ -53,7 +53,9 @@ ("+ a", "+ a"), # UAdd ("- 1", "- 1"), # UnaryOp ("- a", "- a"), # USub - ("(1, 2, 3)", "(1, 2, 3)"), # Tuple + ("(1, 2, 3)", "(1, 2, 3)"), # Tuple + ("(1,)", "(1,)"), # Tuple (single element) + ("((1,),)", "((1,),)"), # Tuple (nested single element) ("()", "()"), # Tuple (empty) ]) def test_unparse(source, expected):