【问题标题】:How to remove static class variable using automodule with Sphinx?如何使用带有 Sphinx 的自动模块删除静态类变量?
【发布时间】:2020-05-09 19:09:17
【问题描述】:

我目前正在使用 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:

【问题讨论】:

  • 第二个.. autoclass: 中的:noindex: 选项仅用于防止Sphinx 发出警告以使用.. autoclass: 记录YourClass 两次,因为这会导致通用索引中出现重复条目​​。

标签: python python-sphinx member docstring autodoc


【解决方案1】:

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

除非严格需要在模块导入时阻止变量自初始化,否则因为您想要呈现它的方式而更改您的 Python 源代码是不正确的。如果您的 Python 源代码正确,则调整您的 .rst 文件以自定义演示文稿。

your_module.py

from pathlib import Path


class YourClass:

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

your_module.rst(显示 2 种可能的方式)。

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.

结果:

【讨论】:

  • 这确实是我想要的谢谢!通过我的尝试,我非常接近您的解决方案,但我不断收到重复引用的警告,仅仅是因为我没有从模块中排除该类!
【解决方案2】:

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

例如:

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

【讨论】:

  • 不幸的是,即使使用您建议的解决方法,该值仍然会打印到输出中
猜你喜欢
  • 1970-01-01
  • 2013-03-31
  • 2023-03-18
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多