我有一个模块应该有@property
,我通过设置一个类作为模块解决了这个问题。我从这个答案中得到了这个想法:惰性模块变量——可以做到吗? https://stackoverflow.com/questions/1462986/lazy-module-variables-can-it-be-done/1463773#1463773
我希望它是可重复且易于使用的,所以我为它创建了一个元类。这就像一个魅力。
问题是,当使用 Sphinx 生成文档属性时,不会记录属性。其他一切都按预期记录。我不知道如何解决这个问题,也许这是 Sphinx 的问题?
该模块:
import sys
import types
class ClassAsModule(type):
def __new__(cls, name, bases, attrs):
# Make sure the name of the class is the module name.
name = attrs.pop('__module__')
# Create a class.
cls = type.__new__(cls, name, bases, attrs)
# Instantiate the class and register it.
sys.modules[name] = cls = cls(name)
# Update the dict so dir works properly
cls.__dict__.update(attrs)
class TestClass(types.ModuleType):
"""TestClass docstring."""
__metaclass__ = ClassAsModule
@property
def some_property(self):
"""Property docstring."""
pass
def meth():
"""meth doc"""
pass
以及复制粘贴来生成/查看 Sphinx 文档:
sphinx-apidoc . -o doc --full
sphinx-build doc html
xdg-open html/module.html
最重要的部分是记录类的属性。奖励点还记录原始模块成员。
EDIT:该类应记录为它所在的模块。该类以这种方式使用,因此在 Sphinx 中也应以这种方式显示。
所需输出的示例:
Module Foo
TestClass docstring.
some_property
Property docstring.
meth()
meth doc
EDIT 2:我发现了一些可能有助于找到解决方案的东西。当有常规模块时foo
包含以下内容:
#: Property of foo
prop = 'test'
Sphinx 的文档如下:
foo.prop = 'test'
Property of foo
同样的工作如果prop
是一个类的属性。我还没有弄清楚为什么它在我的特殊情况下不起作用。