Search code examples
pythonpython-sphinxpython-decoratorsautodoc

Sphinx decorated classes not documented


I'm documenting my library with Sphinx. And I have decorator logic_object:

class logic_object:
    """Decorator for logic object class.
    """
    def __init__(self, cls):
        self.cls = cls
        self.__doc__ = self.cls.__doc__

And I have gravity class that decorated by logic_object:

@logic_object
class gravity:
    """Basic gravity object logic class.

    :param float g: pixels of acceleration
    :param float jf: jump force
    """
#There is more not important code.

My Sphinx .rst file is:

Mind.Existence
========================
Classes, methods and functions marked with * aren't for usual cases, they are made to help to the rest of the library.

.. automodule:: Mind.Existence
   :members:
   :member-order: bysource

logic_object gets documented with autodoc, but gravity doesn't.

Why this happens and how to fix it?


Solution

  • It is because the decorated class is not a real class object (not an instance of type), and therefore autodoc does not know how to document it.

    To fix it, you must write a custom documenter (e.g. in your conf.py):

    from Mind.Existence import logic_object
    from sphinx.ext.autodoc import ClassDocumenter
    
    class MyClassDocumenter(ClassDocumenter):
        objtype = 'logic_object'
        directivetype = 'class'
    
        @classmethod
        def can_document_member(cls, member, membername, isattr, parent):
            return isinstance(member, logic_object)
    
    def setup(app):
        app.add_autodocumenter(MyClassDocumenter)
    

    And then (in your decorator) you must also copy __name__ and __bases__ from the decorated object::

    def __init__(self, cls):
        self.cls = cls
        self.__doc__ = cls.__doc__
        self.__name__ = cls.__name__
        self.__bases__ = cls.__bases__