8

I'm trying to get my Sphinx documentation build correctly and have cross-references (including those from inherited relations) work right.

In my project, I have a situation which is depicted in the example below, which I replicated for convenience on this github repo:

$ tree .
.
├── a
│   ├── b
│   │   └── __init__.py
│   └── __init__.py
├── conf.py
├── index.rst
└── README.md

In a.b.__init__, I declare classes A and B. B inherits from A. In a.__init__, I import A and B like: from .b import A, B. The reason I do this in my real projects is to reduce the import paths on modules while keeping implementation of specific classes in separate files.

Then, in my rst files, I autodoc module a with .. automodule:: a. Because a.b is just an auxiliary module, I don't autodoc it since I don't want to get repeated references to the same classes and not to confuse the user on what they should be really doing. I also set show-inheritance expecting a.B will have a back link to a.A.

If I try to sphinx-build this in nit-picky mode, I'll get the following warning:

WARNING: py:class reference target not found: a.b.A

If I look at the generated documentation for class B, then I verify it is not properly linked against class A, which just confirms the warning above.

Question: how do I fix this?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
André Anjos
  • 4,641
  • 2
  • 27
  • 34
  • 2
    It works if you add `A.__module__ = "a"` in `a/__init__.py`. This is similar to http://stackoverflow.com/q/22096187/407651. – mzjn Oct 13 '16 at 16:25
  • Indeed, that works. Care to fill in an answer so I can point to the solution? – André Anjos Oct 14 '16 at 08:07

1 Answers1

9

Sphinx uses the value of the __module__ attribute to figure out the name of the module in which a class/function/method was defined (see https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy). Sometimes this is not what you want in the documentation.

The attribute is writable. Your problem can be fixed by adding this line in a/__init__.py:

A.__module__ = "a"
mzjn
  • 48,958
  • 13
  • 128
  • 248
  • Note that this can also be defined at the class level by setting `__module__ = "a"` inside the class definition. Looks a bit cleaner imo. – Adam Stewart Jun 30 '21 at 15:57