简体   繁体   English

如何为sphinx文档保留装饰类的文档字符串?

[英]How to preserve a docstring of a decorated class for sphinx documentation?

I have a decorator that has a nested definition of the wrapping class. 我有一个装饰器,它有一个包装类的嵌套定义。 Wrapper maintains as the attribute the original class that it wraps. 包装器将其包装的原始类维护为属性。 Toy example looks like this: 玩具示例如下所示:

def decorator(cls):
    class Wrapper(object):
        original = cls

        def __init__(self):
            self.__doc__ = self.original.__doc__
            self.__name__ = self.original.__name__

        def do_something_with_cls(cls):
            pass

    return Wrapper

Now I want to decorate the Foo class with this decorator in the other module and generate sphinx documentation for the Foo class before it has been decorated. 现在我想在另一个模块中使用这个装饰器来装饰Foo类,并在装饰之前为Foo类生成sphinx文档。 It looks like this: 它看起来像这样:

from .bar import decorator


@decorator
class Foo(object):
    """The docstring I want to preserve."""
    def __init__(self):
        pass

I was trying to achieve this with use of the autoclass functionality but it didn't work out. 我试图通过使用autoclass功能实现这一点,但它没有成功。 What i wanted to do was to create a class instance and take its docstring: 我想要做的是创建一个类实例并获取其文档字符串:

.. autoclass:: package.baz.Foo()
   :members:

but it returned this in the html documentation of the package.baz.Foo class: alias of package.bar.decorator.<locals>.Wrapper 但它在package.baz.Foo类的html文档中返回了这个: alias of package.bar.decorator.<locals>.Wrapper

I want to achieve that when I am documenting the baz module I am able to generate a documentation of the Foo class before its decoration. 我想要实现这一点,当我记录baz模块时,我能够在装饰之前生成Foo类的文档。 Is it possible? 可能吗?

EDIT: 编辑:

This looks like a similar problem but here what I would like to achieve is to pass to the Wrapper instance the docstring that Sphinx will see and generate a documentation basing on the original Foo docstring or I will be able to call a Wrapper.original and make a documentation of this, but the following didn't work out: 看起来像一个类似的问题,但在这里我想要实现的是将Sphinx将看到的文档字符串传递给Wrapper实例,并根据原始的Foo文档字符串生成文档,或者我将能够调用Wrapper.original并制作这方面的文档,但以下没有成功:

.. autoclass package.baz.Foo.original
   :members:

If @wraps is not working you can update __doc__ manually. 如果@wraps不起作用,您可以手动更新__doc__

Do something like: 做类似的事情:

def decorator(cls):
    class Wrapper(object):
        original = cls

        def __init__(self):
            self.__doc__ = self.original.__doc__
            self.__name__ = self.original.__name__

        def do_something_with_cls(cls):
            pass

    Wrapper.__doc__ = cls.__doc__
    return Wrapper


@decorator
class Foo(object):
    """The docstring I want to preserve."""
    def __init__(self):
        pass


print(Foo.__doc__)

'The docstring I want to preserve.' “我想保留的文档字符串。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM