Skip to content

Allow setting audodoc default options in conf - #5215

Merged
tk0miya merged 3 commits into
sphinx-doc:masterfrom
LewisHaley:lewis/allow-setting-audodoc-default-options-in-conf
Aug 18, 2018
Merged

tk0miya merged 3 commits into
sphinx-doc:masterfrom
LewisHaley:lewis/allow-setting-audodoc-default-options-in-conf

Conversation

@LewisHaley

Copy link
Copy Markdown
Contributor

Subject: Set global default values for directives in config

Feature or Bugfix

  • Feature

Purpose

  • In RST files, you can set, for example: :special-members: __init__, __iter__. In config, you can set this flag, but only to include all special members, by including it in a list autodoc_default_flags. This PR make it so you can set the same values in global config as you can individually in RST files.

Detail

  • I wanted to write a test for this but I couldn't get the existing setup in test_autodoc to work for me, because autodoc.directives.process_documenter_options wants a options object which in the unit tests is mocked to a Struct, which doesn't work with process_documenter_options.
  • I have managed to use this code to produce the docs for my own project, and it worked as expected using
autodoc_default_values = {
    'members': None,
    'undoc-members': None,
    'special-members': None,
    'show-inheritance': None,
    'member-order': 'bysource',
    'exclude-members': '__dict__,__weakref__,__module__',
}

in conf.py

Relates

@LewisHaley
LewisHaley force-pushed the lewis/allow-setting-audodoc-default-options-in-conf branch from b9e28bc to 692a0b3 Compare July 26, 2018 13:16
@codecov

codecov Bot commented Jul 26, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #5215 into master will increase coverage by 0.01%.
The diff coverage is 88.34%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5215      +/-   ##
==========================================
+ Coverage   82.26%   82.28%   +0.01%     
==========================================
  Files         302      302              
  Lines       39864    39961      +97     
  Branches     6153     6163      +10     
==========================================
+ Hits        32794    32880      +86     
- Misses       5727     5734       +7     
- Partials     1343     1347       +4
Impacted Files Coverage Δ
sphinx/ext/autodoc/directive.py 84.61% <100%> (ø) ⬆️
tests/roots/test-ext-autodoc/target/__init__.py 78% <50%> (-2.44%) ⬇️
sphinx/ext/autodoc/__init__.py 86.32% <76.47%> (ø) ⬆️
tests/test_autodoc.py 96.46% <94.8%> (-0.29%) ⬇️
sphinx/__init__.py 57.5% <0%> (-2.5%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9cddc34...f196a92. Read the comment docs.

@tk0miya

tk0miya commented Jul 28, 2018

Copy link
Copy Markdown
Member

As discussed in #4076, it would be better to enhance autodoc_default_flags to accept both list and dict:

autodoc_default_flags = [
    'members', 'undoc-members', ...
]

or

autodoc_default_flags = {
    'members': None,
    'undoc-members': None,
    ...
    'exclude-members': '__dict__,__weakref__,__module__',
}

Since 1.8, Sphinx provides config-inited event. I think it is good for conversion.
For example, HTML builder installs a converter for html_js_files:

sphinx/sphinx/builders/html.py

Lines 1605 to 1620 in 8ddca8c

def convert_html_js_files(app, config):
# type: (Sphinx, Config) -> None
"""This converts string styled html_js_files to tuple styled one."""
html_js_files = [] # type: List[Tuple[unicode, Dict]]
for entry in config.html_js_files:
if isinstance(entry, string_types):
html_js_files.append((entry, {}))
else:
try:
filename, attrs = entry
html_js_files.append((filename, attrs))
except Exception:
logger.warning(__('invalid js_file: %r, ignored'), entry)
continue
config.html_js_files = html_js_files # type: ignore

@tk0miya

tk0miya commented Jul 28, 2018

Copy link
Copy Markdown
Member

I just made #5223 for better testing (I'll merge it soon). I hope this helps this case.

@tk0miya tk0miya added type:enhancement enhance or introduce a new feature extensions:autodoc labels Jul 28, 2018
@tk0miya tk0miya added this to the 1.8.0 milestone Jul 28, 2018
@LewisHaley

Copy link
Copy Markdown
Contributor Author

I didn't like the idea of overloading autodoc_default_flags because (to me, at least) "flags" implies on/off only (which is how the option currently behaves - if "members" is present then "members = True", else "members = False"). I think the idea of giving arguments to "flags" is perhaps more confusing than just adding a new option. The old option could always be deprecated eventually.

But I'm happy to follow your suggestion of using the converter function with the original option name.
Thanks for the unittest - I'll try to follow it's example.

@tk0miya

tk0miya commented Aug 7, 2018

Copy link
Copy Markdown
Member

OMG, I just made #5277 as an alternative of this PR. Okay, let's discuss what is the best way to configure the default settings. I'll reconsider this later (It's time to sleep in japan 😄 ).

@shimizukawa Please let me know your opinion.

@LewisHaley
LewisHaley force-pushed the lewis/allow-setting-audodoc-default-options-in-conf branch 2 times, most recently from f14c54c to 73b93f2 Compare August 8, 2018 16:38
@LewisHaley

Copy link
Copy Markdown
Contributor Author

I've made the changes to use config-inited and the conversion hook.
I found a latent bug in the autodoc tests when I added some new tests, which I've fixed: 50ad4f1.

I've added a load of tests for this, partly because the different combinations of options can be quite surprising. I found testing the diff between option on/off was the best for showing what the full effect is of each of the options/values.

@LewisHaley
LewisHaley force-pushed the lewis/allow-setting-audodoc-default-options-in-conf branch 4 times, most recently from 33a83a2 to 0c344b1 Compare August 8, 2018 21:23
@shimizukawa

Copy link
Copy Markdown
Member

+1 for autodoc_default_values. autodoc_default_options is better to me because :members: is a option of autodoc directive.

@tk0miya

tk0miya commented Aug 16, 2018

Copy link
Copy Markdown
Member

Okay, let's make it an alias of autodoc_default_flags on next step.

@tk0miya tk0miya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM with nits

Comment thread sphinx/ext/autodoc/__init__.py Outdated
from docutils.utils import Reporter # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA
from sphinx.config import Config # NOQA

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems duplicated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

Comment thread tests/test_autodoc.py Outdated

# with :special-members:
# Note that :members: must be *on* for :special-members: to work.
# TODO Is this a bug?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK, it's well-known behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed TODO comment

Comment thread tests/test_autodoc.py Outdated


@pytest.mark.sphinx('html', testroot='ext-autodoc')
@pytest.mark.parametrize('target, options, expected_diff', [

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel this parameterized test is hard to understand...
Could you change this to simple testcases?

In addition, is doing diff important for this case? We've already done testing for each options. So I think the main purpose of this case is autodoc_default_flags modifies the options of each autodoc results.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I found the diffs useful for myself as I wasn't completely familiar with what each option did but, as you say, there are tests for this already. I've left the tests quite verbose but they don't use parametrize or look at the diffs.

Setting mutable types as default arguments is bad practice because the
value is only initialised once. This means that defaults arguments of
lists and dictionaries which are modified during code execution *stay*
modified between calls.

In this case, the `options` dictionary accumulated options as more and
more test cases were executed. Without this change, the tests added in
the next commit do not pass.

See: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument
Previously, users could specify a *list* of flags in their config files.
The flags were directive names that would otherwise be present in the
.rst files. However, as a list, it was not possible to specify values
to those flags, which *is* possible in .rst files.

For example, in .rst you could say

  :special-members: __init__, __iter__

And this would cause autodoc to generate documents for these methods that
it would otherwise ignore.

This commit changes the config option to instead accept a dictionary.
This is a dictionary whose keys can contain the same flag-names as before,
but whose values can contain the arguments as seen in .rst files.

The old list is still supported, for backwards compatibility, but the data
is transformed into a dictionary when the user's config is loaded.
As the previous commit explains, it is now possible to specify arguments
to the global options in config files. This means that we can now include
the `exclude-members` option in this global configuration.

Previously, there was no point including this option because it makes no
sense without arguments. Including this option means users have the
flexibility of explicitly including which special methods they want using
(e.g.):

  :special-members: __init__, __iter__

or explicitly excluding which special-members (or other members) they want
using (e.g.):

  :exclude-members: __weakref__, __hash__
@LewisHaley
LewisHaley force-pushed the lewis/allow-setting-audodoc-default-options-in-conf branch from 0c344b1 to f196a92 Compare August 17, 2018 15:03
@LewisHaley

Copy link
Copy Markdown
Contributor Author

Re. future work about making an alias for the option so its name makes more sense, could I suggest as well that the accepted types for the dict is more tightly defined. For example, :undoc-members: would make more sense as only allowing True/False, while :exclude-members: only make sense as a list of strings (if the list is empty, nothing is excluded).

:members:, :special-members: are more difficult because they need a "say yes to everything" as well as a limiting list. You could use {'members': ["*"]} (meaning glob) to include everything? This way, the values in the dictionary are always a list of strings.

Just some thoughts I've had. :)

@tk0miya
tk0miya merged commit 00072ec into sphinx-doc:master Aug 18, 2018
@tk0miya

tk0miya commented Aug 18, 2018

Copy link
Copy Markdown
Member

Just merged!
Thank you for contribution!

@LewisHaley
LewisHaley deleted the lewis/allow-setting-audodoc-default-options-in-conf branch August 21, 2018 14:52
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Aug 27, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

extensions:autodoc type:enhancement enhance or introduce a new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants