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