【发布时间】:2013-03-31 13:46:54
【问题描述】:
我有一个模块应该有一个@property,我通过将一个类设置为模块解决了这个问题。我从这个答案中得到了这个想法:Lazy module variables--can it be done?
我希望这是可重复且易于使用的,因此我为它制作了一个元类。这就像一个魅力。
问题是当使用 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
最重要的部分是记录类的属性。奖励积分还可以记录原始模块成员。
编辑:该类应记录为它所在的模块。该类以这种方式使用,因此应该以这种方式出现在 Sphinx 中。
所需输出示例:
Module Foo
TestClass docstring.
some_property
Property docstring.
meth()
meth doc
编辑 2: 我发现了一些可能有助于找到解决方案的东西。当具有以下内容的常规模块foo 时:
#: Property of foo
prop = 'test'
Sphinx 记录如下:
foo.prop = 'test'
Property of foo
如果prop 是类的属性,则同样有效。我还没弄清楚为什么它在我的特殊情况下不起作用。
【问题讨论】:
-
您的代码不起作用。
ModMeta未定义。你能发布工作代码吗? -
@jterrace 复制粘贴失败。现在已修复;-)
-
删除了我的答案,因为您的原始代码有
__metaclass_而不是__metaclass__,导致它不起作用。 -
你确定这真的像你想象的那样工作吗?方法/属性似乎无法访问模块命名空间。例如,如果我将
meth()中的pass语句替换为return sys.path,我会得到:AttributeError: 'NoneType' object has no attribute 'path'如果我只返回“Hello”或类似的东西,但不能访问应该是全局变量,则效果很好。跨度> -
你看到和我一样的行为吗?
标签: python properties python-sphinx metaclass python-module