如何使用带Sphinx的automodule删除静态类变量?

2024-04-19 08:05:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用Sphinx(第一次使用它)为我的模块构建文档,我有一些类,它们有一些用默认值初始化的类变量

例如:

class ConfigSettings(object):
    """Class that manages a config file
    """    
    #: Contains the path to the config file (root dir of module)
    path = Path(util.getAbsCurrentPath('configfile.ini'))

在构建文档时,会对变量进行求值,并打印我不想要的文件的完整路径(出于安全原因)。 有没有一种方法可以不显示变量值,而只显示使用Sphinx的注释

我尝试了.. autoclass:.. autodata:的各种组合,但到目前为止没有一种有效

这是我当前在生成文件中的内容:

Config module
----------------------------

.. automodule:: lib.config
   :members:
   :undoc-members:
   :show-inheritance:

Tags: 模块文件thepath文档configthatobject
2条回答

您可以通过在导入时不计算路径来解决此问题。我认为最好的方法是使用classproperty

例如:

class ConfigSettings(object):
    @classproperty
    def path(cls):
        return Path(util.getAbsCurrentPath('configfile.ini'))

使用Sphinx指令最简单的方法是使用注释或排除成员

除非严格要求在模块导入时停止变量自初始化,否则更改Python源代码是不正确的,因为您希望以这种方式显示它。如果您的Python源代码是正确的,则调整.rst文件以自定义表示

您的_module.py

from pathlib import Path


class YourClass:

    #: This comment is documented with the member.
    path = Path('your_path', 'configfile.ini')

您的_module.rst(显示了两种可能的方式)

your_module
===========

.. automodule:: your_module
    :exclude-members: YourClass

    .. autoclass:: YourClass
        :exclude-members: path

        In this example you use an annotation while excluding from autoclass.

        .. autoattribute:: path
            :annotation: ='write your path here'

    .. autoclass:: YourClass
        :noindex:
        :exclude-members: path

        In this example you simply exclude from autoclass.

结果是:

enter image description here

相关问题 更多 >