如何使 Python/Sphinx 文档对象属性仅在 __init__ 中声明?
我有带有对象属性的 Python 类,这些属性仅在运行构造函数时声明,如下所示:
class Foo(object):
def __init__(self, base):
self.basepath = base
temp = []
for run in os.listdir(self.basepath):
if self.foo(run):
temp.append(run)
self.availableruns = tuple(sorted(temp))
如果我现在使用 help(Foo)
或尝试在中记录 Foo
Sphinx、self.basepath
和 self.availableruns
属性未显示。这对于我们 API 的用户来说是一个问题。
我尝试寻找一种标准方法来确保解析器可以找到这些“动态声明”属性(最好是文档字符串),但到目前为止还没有运气。有什么建议吗?谢谢。
I have Python classes with object attributes which are only declared as part of running the constructor, like so:
class Foo(object):
def __init__(self, base):
self.basepath = base
temp = []
for run in os.listdir(self.basepath):
if self.foo(run):
temp.append(run)
self.availableruns = tuple(sorted(temp))
If I now use either help(Foo)
or attempt to document Foo
in Sphinx, the self.basepath
and self.availableruns
attributes are not shown. That's a problem for users of our API.
I've tried searching for a standard way to ensure that these "dynamically declared" attributes can be found (and preferably docstring'd) by the parser, but no luck so far. Any suggestions? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们永远不会被任何解析器“检测到”。
Python 有
setattr
。从任何意义上来说,完整的属性集永远不会“可检测到”。您绝对必须在文档字符串中描述它们。
[除非你想做一堆元编程来从你从
inspect
或其他东西收集的东西生成文档字符串。即使如此,一旦您开始使用setattr
,您的“解决方案”就会不完整。]They cannot ever be "detected" by any parser.
Python has
setattr
. The complete set of attributes is never "detectable", in any sense of the word.You absolutely must describe them in the docstring.
[Unless you want to do a bunch of meta-programming to generate docstrings from stuff you gathered from
inspect
or something. Even then, your "solution" would be incomplete as soon as you starting usingsetattr
.]您可以定义一个与实例变量同名的类变量。当您设置该类变量时,该类变量将被实例变量隐藏。例如:
确实,如果实例变量具有有用的不可变默认值(例如 None 或空元组),那么您可以通过不设置变量(如果应该具有默认值)来节省一点内存。当然,如果您正在谈论可能想要删除的实例变量(例如
del foo.availableruns
),则这种方法将不起作用 - 但我发现这不是很常见的情况。如果您使用的是 sphinx,并且设置了“自动属性”,那么这应该得到适当的记录。或者,根据您正在执行的操作的上下文,您可以直接使用 Sphinx
.. py:attribute::
指令。You could define a class variable with the same name as the instance variable. That class variable will then be shadowed by the instance variable when you set it. E.g:
Indeed, if the instance variable has a useful immutable default value (eg None or the empty tuple), then you can save a little memory by just not setting the variable if should have its default value. Of course, this approach won't work if you're talking about an instance variable that you might want to delete (e.g.,
del foo.availableruns
)-- but I find that's not a very common case.If you're using sphinx, and have "autoattribute" set, then this should get documented appropriately. Or, depending on the context of what you're doing, you could just directly use the Sphinx
.. py:attribute::
directive.