gpt4 book ai didi

python - 使用带有 :Example: 的 Sphinx doctest

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:54 26 4
gpt4 key购买 nike

考虑以下函数:

# in mymodule.py:

def myfunc(num,mystring):
"""
replicates a string

:param num: a positive integer
:param mystring: a string
:return: string concatenated with itself num times

:Example:
>>> num = 3
>>> mystring = "lol"
>>> myfunc(num, mystring)
"lollollol"
"""
return num*mystring

如何让 Sphinx doctest 工作,以验证中的示例代码

:示例:´ 实际上有效吗?
每当我运行
make doctest`

它表示运行了 3 个测试,但有 1 个失败。删除最后两行,从

开始

myfunc(num, mystring),

它说 2 个测试已成功运行。所以我一定是在那条线上做错了什么。但是什么?

编辑 这是完整代码的终端输出(回溯);似乎不知何故它找不到我为其编写文档字符串并且正在运行 doctest 的函数:

Running Sphinx v1.8.3
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [doctest]: targets for 1 source files that are out of date
updating environment: [] 0 added, 1 changed, 0 removed
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
running tests...

Document: index
---------------
**********************************************************************
File "index.rst", line ?, in default
Failed example:
myfunc(num, mystring)
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python3.6/doctest.py", line 1330, in __run
compileflags, 1), test.globs)
File "<doctest default[2]>", line 1, in <module>
myfunc(num, mystring)
NameError: name 'myfunc' is not defined
**********************************************************************
1 items had failures:
1 of 3 in default
3 tests in 1 items.
2 passed and 1 failed.
***Test Failed*** 1 failures.

Doctest summary
===============
3 tests
1 failure in tests
0 failures in setup code
0 failures in cleanup code
build finished with problems.
Makefile:19: recipe for target 'doctest' failed

最佳答案

Sphinx+doctest 没有导入模块。您可以在文档字符串中帮助他:

    :Example:
>>> from mymodule import myfunc
>>> myfunc(3, 'lol')
'lollollol'

或者在 conf.py 中添加:

doctest_global_setup = '''
#if required, modif sys.path:
import sys
sys.path.append('../directory_containing_mymodule/')
from mymodule import *
'''

比照。 https://www.sphinx-doc.org/en/master/usage/extensions/doctest.html

我很想听听是否有更简单的答案。

关于python - 使用带有 :Example: 的 Sphinx doctest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58189699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com