如何使用 pdoc 为包含私有/受保护类的 Python 项目生成文档

问题描述

我正在尝试按照此 article 为我的带有 pdoc 模块的 Python 项目生成文档。

我注意到生成的文档中缺少以 __ 开头的所有类、方法等(私有/受保护的)。

这是sample.py

class __Members:
    def __test():
        pass

class seedoc:
    ''' see me '''
    pass

这就是我用 pdoc 生成文档的方式

$pdoc --html sample.py
html/sample.html

根据此屏幕截图,我在生成的文档中只看到公共类:

enter image description here

有人能帮我想出一种方法来克服这个限制并生成所有私有/受保护成员的文档吗?提前致谢。

解决方法

按照惯例,仅 Pdoc extracts public API members(不以下划线为前缀)。

您可以在模块级别通过定义 __all__ 或更一般地通过在 __pdoc__ dict 中指定覆盖来覆盖此行为,手动或自动为少数成员但有点骇人听闻,有点像:

# Specified at the end of each module that contains private
# classes/methods that need to be exposed
__pdoc__ = {name: True
            for name,klass in globals().items()
            if name.startswith('_') and isinstance(klass,type)}
__pdoc__.update({f'{name}.{member}': True
                 for name,klass in globals().items()
                 if isinstance(klass,type)
                 for member in klass.__dict__.keys()
                 if member not in {'__module__','__dict__','__weakref__','__doc__'}})

或者,如果您的成员是您的公共 API 的一部分,您应该只重命名它们。

另请注意,Python 默认在对象上定义 dozens of dunder members,其中大多数具有标准含义或内部含义:

>>> class Cls:
...     pass

>>> dir(Cls)
['__class__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__init_subclass__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__']