Search code examples
pythontuplespython-sphinxdefault-arguments

How to include a tuple in a ..class :: signature as default argument?


I'm unable to format a tuple as a default argument properly:

.. class:: OutputFunc(args=('value',))

This is displayed in the HTML output without the tuple parentheses args='value'.

If I add backslashes:

.. class:: OutputFunc(args=\('value',\))

they are rendered: args=\('value', \),

Update: I found this in the sphinx docs, probably there is no solution.

Default values for optional arguments can be given (but if they contain commas, they will confuse the signature parser)


Solution

  • There are a number of ways to solve this, the problem is particular to using a singleton tuple literal as default argument.

    This is displayed in the HTML output without the tuple parentheses args='value'.

    Using sphinx-build 3.5.2 with Python 3.9.0 the parentheses do render, only the comma disappears.

    .. class:: OutputFunc(args=('value',))
    

    enter image description here

    One alternative is to use the tuple constructor instead of the literal.

    .. class:: OutputFunc(args=tuple('value'))
    

    enter image description here

    It's worth mentioning the problem only happens when the literal is a singleton.

    .. class:: OutputFunc(args=('value', 'value2'))
    

    enter image description here

    Finally a solution that retains the comma and the parenthesis is using an invisible Unicode character after the comma, in this example I used U+200B (the zero-with space character). However other characters could be used (credit to @mzjn the idea was taken from one of his posts.)

    .. class:: OutputFunc(args=('value', insert U+200B ZWSP character here))
    

    enter image description here

    EDIT: After OP feedback.

    Apparently using older sphinx-build versions adding more parameters will again cause the bug even with the zero-width whitespace. The easiest solution is updating to a recent Sphinx version in which case the above workaround works even if using multiple parameters.

    .. class:: OutputFunc(args=('value',​), debug=False)
    

    enter image description here