我正在尝试提取 Python 模块中所有文档字符串的开始和结束行号。有没有一种明智的方法可以在不使用正则表达式的情况下做到这一点?
假设我有一个带有文档字符串的函数,其中我将返回类型声明为带有两个字符串的元组:
def foo():
"""
Returns:
Tuple[str, str]: Tuple of first name and last name
"""
Run Code Online (Sandbox Code Playgroud)
如果我不在文档字符串之外的任何地方使用它,Tuple我是否应该导入它?typing
我编写测试函数。在文档字符串中,我通常提到测试用例名称作为摘要行。测试用例描述如下。现在我只需要从文档字符串中获取测试用例名称(第一行)。有没有Pythonic的方法来做到这一点?
def test_filesystem_001():
"""This is test case name of test_filesystem_001.
[Test Description]
-Create a file
-write some data
-delete it
"""
pass
Run Code Online (Sandbox Code Playgroud)
所以我需要一种方法来打印文档字符串的第一行,即“这是 test_filesystem_001 的测试用例名称”。提前致谢。
我想提供代码片段来展示如何在 python 中使用特定的方法或类。我怎样才能做到这一点?
在 Java 中可以<pre> ... </pre>这样做。
Doctest是唯一的方法吗? 当我查看典型包(例如 pandas、numpy 等)的现有文档字符串时,除了 doctest 之外,我从未见过任何其他内容,它旨在测试该方法,而不仅仅是将文本格式化为 python 代码。那么,如果 doctest 是唯一的方法,那么将代码片段格式化为交互式 python 会话的正确方法是什么?我不想每次都在交互式会话中编写代码,然后将其 c+p 到我的文档字符串中。好像不太对劲。
我想这样做:
FOO_CONSTANT = 1
def foo():
"""asdf """ + str(FOO_CONSTANT)
print(foo.__doc__)
Run Code Online (Sandbox Code Playgroud)
哪个应该打印:
asdf 1
Run Code Online (Sandbox Code Playgroud)
但相反它打印
None
Run Code Online (Sandbox Code Playgroud)
我可以获得预期的输出
FOO_CONSTANT = 1
def foo():
"""asdf """
foo.__doc__ += str(FOO_CONSTANT)
print(foo.__doc__)
Run Code Online (Sandbox Code Playgroud)
但是将文档字符串分散到代码中感觉很糟糕。
是否可以在文档字符串中包含常量的值?
PS:我发现这是远程相关的。尝试的方法也不会生成有效的文档字符串,请注意,它是关于生成动态文档字符串,而 myFOO_CONSTANT预计不会更改。我只是想避免重复自己。该名称FOO_CONSTANT对于文档字符串的读者来说没有任何意义,但该值却具有意义,并且它出现在几个我不想重复的文档字符串中。
我正在尝试记录一个具有一些类级成员变量的 Python 类,但我无法使用 reST/Sphinx 对其进行适当记录。
代码是这样的:
class OSM:
"""Some blah and examples"""
url = 'http://overpass-api.de/api/interpreter' # URL of the Overpass API
sleep_time = 10 # pause between successive queries when assembling OSM dataset
Run Code Online (Sandbox Code Playgroud)
但我得到了这个输出(请参见绿色圆圈区域,我希望在其中有一些描述这两个变量的文本,如上所述)。

对于模糊之处,我深表歉意,但示例的一部分有些敏感
restructuredtext docstring python-sphinx autodoc sphinx-napoleon
我一直在寻找是否可以在 VSCode 中为 Python 创建相同的行为来显示字符串参数输入,就像在 JavaScript 中使用 jsdoc 一样。
使用 JSDoc 的 JavaScript 示例:
/**
* @method someMethod
* @description A special method.
* @param { "option1" | "option2" } param1 Choose an option.
*/
function someMethod(param1) {
console.log(param1);
}
Run Code Online (Sandbox Code Playgroud)
因此,在调用该方法时,VSCode 将为 param1 提供自动完成选项。
所以我正在寻找一个Python等效项,最好使用谷歌文档字符串格式:
def some_method(param1: str) -> None:
"""A special method.
Args:
param1 (str): Choose an option. # HOW CAN WE ADD INTELLISENSE OPTIONS HERE??
"""
print(param1)
Run Code Online (Sandbox Code Playgroud) 要使用 Python Sphinx 生成文档,我必须使用特定的文档字符串格式。
VS Code 扩展autoDocstring能够生成这种特定格式,但如果该函数包含多行字符串,则它不起作用。
本例中的示例有效:
def func(param1, param2, param3):
# docstring nicely generated
"""_summary_
:param param1: _description_
:type param1: _type_
:param param2: _description_
:type param2: _type_
:param param3: _description_
:type param3: _type_
:return: _description_
:rtype: _type_
"""
random_variable = 42
string_variable = "not a multiline string"
return string_variable
Run Code Online (Sandbox Code Playgroud)
但在这种情况下无法生成自动文档字符串:
def func(param1, param2, param3):
# doesn't work
""""""
random_variable = 42
string_variable = """
a
multiline
string
"""
return string_variable
Run Code Online (Sandbox Code Playgroud)
有人知道一个技巧,或者让它发挥作用的东西吗?我在函数中使用了很多多行 SQL 字符串,如果我必须提取这些字符串才能使其正常工作,那么我需要进行大量重构。
我几乎有我想要的......
此动态对象使用动态docstring生成封装通用函数调用:
def add_docs(tool):
def desc(func):
func.__doc__ = "Showing help for %s()" % tool
return func
return desc
class Dynamic(object):
def __getattr__(self, value):
@add_docs(value)
def mutable_f(*args, **kwargs):
print "Calling:", value
print "With arguments:", args, kwargs
return mutable_f
Run Code Online (Sandbox Code Playgroud)
它按预期工作:
>>> Dynamic().test(1, input='file')
Calling: test
With arguments: (1,) {'input': 'file'}
>>> Dynamic().test.__doc__
'Showing help for test()'
Run Code Online (Sandbox Code Playgroud)
唯一的两个问题是帮助显示mutable_f签名
>>> help(Dynamic().test)
Help on function mutable_f in module __main__:
mutable_f(*args, **kwargs)
Showing help for test()
(END)
Run Code Online (Sandbox Code Playgroud)
并且没有自动完成(我可以在运行中获得有效函数列表,并缓存它,因为该操作很昂贵)
我认为第一个是无法解决的,但我对第二个不太确定.想法?
在以下代码中:
def read_file(filename):
"""
>>> read_file('text.txt')
{'Donald Trump': [('Donald Trump', 'Join me live in Springfield, Ohio!\nLit!!\n', 1477604720, 'Twitter for iPhone', 5251, 1895)]}
"""
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说:
ValueError: line 4 of the docstring for __main__.read_file has inconsistent leading whitespace: 'Lit!!'
Run Code Online (Sandbox Code Playgroud)
是什么原因引起了这个?
docstring ×10
python ×9
autocomplete ×1
autodoc ×1
doctest ×1
dynamic ×1
pycharm ×1
python-2.7 ×1
python-3.x ×1
typing ×1