Reputation: 12743
I have the following docstring:
def progress_bar(progress, length=20):
'''
Returns a textual progress bar.
>>> progress_bar(0.6)
'[##########--------]'
:param progress: Number between 0 and 1 describes the progress.
:type progress: float
:param length: The length of the progress bar in chars. Default is 20.
:type length: int
:rtype: string
'''
Is there a way to tell sphinx
to add the "Default is X" part to the parameters' description if available?
Upvotes: 18
Views: 6950
Reputation: 51
I have adopted Voy's answer and made a package which automatically does this for you. You are very welcome to try it and to report issues.
The following code
def func(x=None, y=None):
"""
Example docstring.
:param x: The default value ``None`` will be added here.
:param y: The text of default value is unchanged.
(Default: ``'Default Value'``)
"""
if y is None:
y = 'Default Value'
pass
will be rendered like this if the default theme is used, and like this with sphinx_rtd_theme
.
Upvotes: 5
Reputation: 1898
defaults to
is the keyword now. See https://github.com/sglvladi/Sphinx-RTD-Tutorial/blob/a69fd09/docs/source/docstrings.rst#the-sphinx-docstring-format
"""[Summary]
:param [ParamName]: [ParamDescription], defaults to [DefaultParamVal]
:type [ParamName]: [ParamType](, optional)
...
:raises [ErrorType]: [ErrorDescription]
...
:return: [ReturnDescription]
:rtype: [ReturnType]
"""
Upvotes: 4
Reputation: 6284
While it is still manual, this is one method I use to stylize the default argument values more distinctly:
Added a ReST substitution: (Where to put it?)
.. |default| raw:: html
<div class="default-value-section"> <span class="default-value-label">Default:</span>
Then used it in docstring:
"""
:type host: str
:param host: Address of MongoDB host. |default| :code:`None`
:type port: int
:param port: Port of the MongoDB host. |default| :code:`None`
"""
and a little styling through custom CSS:
(note that you may need to add some extra rules to this CSS to override the styling of your theme, for instance: html.writer-html5 .rst-content ul.simple li
worked for me)
.default-value-section {
margin-bottom: 6px;
}
.default-value-section .default-value-label {
font-style: italic;
}
.default-value-section code {
color: #666;
}
Note that I haven't tested this method with multiple Sphinx themes and it may need adjustments for other themes. Tested with sphinx_rtd_theme
theme. Also note that this relies on HTML closing that first <div>
automatically which is a bit naughty. Would be sick for ReST to support default parameter values natively.
Upvotes: 1