问题
I have a Python package that I am attempting to document with sphinx-autodoc. My python package has an __init__.py
file that imports a class out from a submodule to make it accessible at the package level.
from a.b.c.d import _Foo as Foo
__all__ = ["Foo"]
If I do this, my (html) documentation is as follows:
a.b.c package
Submodules
a.b.c.d module
[snip documentation of irrelevant public classes within the a.b.c.d module]
Module contents
The c module.
a.b.c.Foo
alias of _Foo
Not super useful since _Foo
is (rightly) undocumented as it is a private class within the a.b.c.d submodule.
I can add the following to my conf.py
which ensures that the private class definition in the module is documented.
def skip(app, what, name, obj, skip, options):
if name == "_Foo":
return False
return skip
Other alternative, but not great things I've tried:
- Rename
a.b.c.d._Foo
toa.b.c.d.Foo
(and then update the import tofrom a.b.c.d import Foo
) -- but then I get the class documented twice, once under the a.b.c.d module heading, and once again under the Module contents heading. - Renaming
a.b.c.d.Foo
toa.b.c.d.MyFoo
and then importing (from a.b.c.d import MyFoo as Foo
) results inMyFoo
being documented, andFoo
being listed as an alias ofMyFoo
.
Ideally I'd like the private definition to remain undocumented, but to have the version imported into the package fully documented. Does anyone know how I might achieve this?
回答1:
Sphinx uses the __name__
and __module__
members of the class, and the __module__
member of the owner of the class to figure out if it is an alias or the real thing. You can trick Sphinx in thinking that your imported class is the real one by setting these members explicitly.
from a.b.c.d import _Foo as Foo
Foo.__module__ = __name__
Foo.__name__ = 'Foo'
来源:https://stackoverflow.com/questions/38765577/overriding-sphinx-autodoc-alias-of-for-import-of-private-class