Skip to content

1-element tuple rendered incorrectly #80

@rowan-stein

Description

@rowan-stein

1-element tuple rendered incorrectly

User request:

Describe the bug
This is a followup to sphinx-doc#7964 which has been addressed in sphinx-doc#8265.

However the special case of a 1-element tuple is still not handled correctly.

(1,) is rendered as (1), but should keep the trailing comma.

To Reproduce
Add a testcase

    ("(1,)", "(1,)"),                           # Tuple (single element)

at tests/test_pycode_ast.py around the tuple cases.

Researcher specification:

  • Root cause:
    • In sphinx/pycode/ast.py, _UnparseVisitor.visit_Tuple joins elements with ", ".join(...) for non-empty tuples, which drops the trailing comma for single-element tuples.
  • Proposed fix:
    • Special-case single-element tuples:
      • If len(node.elts) == 1, return "(" + self.visit(node.elts[0]) + ",)".
      • If not node.elts, return "()".
      • Else, keep current behavior for multi-element tuples.
  • Files/functions to modify:
    • sphinx/pycode/ast.py: class _UnparseVisitor, method visit_Tuple.
  • Tests to add:
    • In tests/test_pycode_ast.py add:
      • ("(1,)", "(1,)") # single-element tuple
      • Optionally ( "((1,),)", "((1,),)" ) # nested single-element tuple
  • Reproduction & expected failure before fix:
    • Run: pytest -q tests/test_pycode_ast.py -k test_unparse
    • Failure snippet for the new case:
      • Expected: (1,)
      • Actual: (1)
      • Assertion diff:
        • (1) != (1,)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions