Rik*_*ggi 6 python string exec python-sphinx
我正在尝试使用 Sphinx 记录我的 python 代码,但我发现记录一些使用exec;实例化的数据的问题。我有一个包含需要实例化的名称和值的表。
所以在我的代码中,我写了一些类似的东西:
my_vars = [{'name': 'var1', 'value': 'first'},
{'name': 'var2', 'value': 'second'}]
for var in my_vars:
exec("{var[name]} = '{var[value]}'".format(var=var))
Run Code Online (Sandbox Code Playgroud)
问题出在 Sphinx 上:因为我只想维护我使用的源代码autodata,所以我的.rst文件中的相应行是:
.. autodata:: mymodule.var1
.. autodata:: mymodule.var2
Run Code Online (Sandbox Code Playgroud)
建成后给了我这个:
mymodule.var1 = 'first'
str(string[, encoding[, errors]]) -> str
Create a new string object from the given encoded string.
encoding defaults to the current default string encoding.
errors can be ‘strict’, ‘replace’ or ‘ignore’ and defaults to ‘strict’.
mymodule.var2 = 'second'
str(string[, encoding[, errors]]) -> str
Create a new string object from the given encoded string.
encoding defaults to the current default string encoding.
errors can be ‘strict’, ‘replace’ or ‘ignore’ and defaults to ‘strict’.
Run Code Online (Sandbox Code Playgroud)
我认为 autodata 会寻找var1.__doc__一个文档字符串,然后找到了str.__doc__(这是之前显示的消息)。
我真的不知道该怎么办,我正在寻找一种不显示丑陋文档字符串的方法(但仍然保持mymodule.var1 = 'first')。
或者更好的方式来展示我自己的文档,比如:(var1 is this.但我不知道把它放在哪里)。
我的建议是:在模块文档字符串中记录变量,而不是尝试从autodata.
mymodule.py:
"""
This module is...
Module variables:
* var1: var1 doc
* var2: var2 doc
"""
my_vars = [{'name': 'var1', 'value': 'first'},
{'name': 'var2', 'value': 'second'}]
for var in my_vars:
exec("{var[name]} = '{var[value]}'".format(var=var))
...
...
Run Code Online (Sandbox Code Playgroud)
您还可以使用信息字段:
"""
:var var1: var1 doc
:var var2: var2 doc
"""
Run Code Online (Sandbox Code Playgroud)
这在某种程度上是可行的,但输出的格式不如用于记录类变量或函数参数的信息字段那么好。
更新:跟进有关str子类化的评论。这对你有用吗?
from collections import UserString
my_vars = [{'name': 'var1', 'value': 'first', "doc": "var1 docstring"},
{'name': 'var2', 'value': 'second', "doc": "var2 docstring"}]
for var in my_vars:
code = """\
{0} = UserString('{1}')
{0}.__doc__ = '{2}'""".format(var["name"], var["value"], var["doc"])
exec(code)
Run Code Online (Sandbox Code Playgroud)