Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

python - How to make Sphinx Respect Importing Classes Into Package with __init__.py

I have a package:

  • foo
    • foo.py
    • bar.py
    • __init__.py

foo.py has a class Foo. In __init__.py I import class Foo so users can do:

from foo import Foo

Sphinx rightly documents Foo as foo.foo.Foo, which is right but confusing to users. How do I get Sphinx to document it as foo.Foo?

It's also important to get the overall module documentation associated with the right module.

Sphinx documents something called:

..module:: module.name

but when I use it in the first comment in a foo.py file, the doc is still attributed to foo.foo.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The value of the __module__ attribute is the name of the module in which a class/function/method was defined (see https://docs.python.org/2.7/reference/datamodel.html). The attribute is writable so it can be redefined in __init__.py:

Foo.__module__ = "foo"

Now if you use .. automodule:: foo, the qualified name of the Foo class will be shown as foo.Foo in the generated module documentation.


As an alternative to __module__-fiddling, you can use autoclass instead of automodule.

.. autoclass:: foo.Foo will produce the wanted output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...