简体   繁体   中英

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)

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',))

在此处输入图像描述

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

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

在此处输入图像描述

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

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

在此处输入图像描述

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))

在此处输入图像描述

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM