Overriding Sphinx autodoc “Alias of” for import of private class?

泪湿孤枕 提交于 2020-01-14 07:24:14

问题


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:

  1. Rename a.b.c.d._Foo to a.b.c.d.Foo (and then update the import to from 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.
  2. Renaming a.b.c.d.Foo to a.b.c.d.MyFoo and then importing (from a.b.c.d import MyFoo as Foo) results in MyFoo being documented, and Foo being listed as an alias of MyFoo.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!