2

Using the source below, i want to generate documentation for the class foo defined in the function.

# module named rubbish.py
def factory():
    class foo:
        def bar(self):
            '''bar
            '''
            pass

the corresponding rst file looks so

rubbish module
==============

.. automodule:: rubbish
    :members:
    :undoc-members:
    :show-inheritance:

and the class documentation does not get generated. The generated html shows only factory().

Is there any directive to document the class too?

goldcode
  • 633
  • 8
  • 21
  • I'm not sure if this is possible. Similar questions: http://stackoverflow.com/q/27337534/407651, http://stackoverflow.com/q/12039633/407651 – mzjn Mar 07 '17 at 16:48

1 Answers1

0

I managed to do this in a perhaps round about way, but it seems to work.

  • I have not tested this "from scratch"
  • I am using autodoc

Code

my_module.py:

# here lies the class factory
def foo_factory():
  class Foo:
    '''My Foo class is cool'''

    def __init__(self):
      '''Init a Foo 
      Params
      ------
      etc..
      '''
      pass

    def bar(self):
      '''do a bar! 
      Params
      ------
      etc..
      '''
      return 1+1
  
  foo_factory.class_example = Foo # <--Note A.1

Add the following to your sphinx conf.py:

def setup(app):
    import my_module
    example = my_module.foo_factory() # <-- Note A.2

    my_module.Foo = my_module.foo_factory.class_example # <--Note A.3
    my_module.Foo.__name__ = 'Foo'# <--Note B.1
    my_module.Foo.__module__ = 'my_module' # <--Note B.2

Add to your module rst file (where the documented class should appear):

.. autoclass:: Foo
   :members:

Explanation

A.1 Make the class accessible outside of the local (foo_factory) scope

A.2 It will only be accessible after invoking the factory, so we "dummy" invoke it here.

The inspiration: https://stackoverflow.com/a/12039980/4996681

A.3 Add the class as an attribute of your module

B After doing the steps in A (and adding the class to the rst file), sphinx did add the class to the documentation, but it appeared as "alias of my_module.foo_factory.<locals>.Foo".

To override the alias, we fool sphinx into thinking the class is a class directly in your module.

The inspiration: https://stackoverflow.com/a/58982001/4996681

Luce
  • 184
  • 2
  • 9