我不建议尝试使用文档字符串做一些复杂的事情。最好保持文档字符串简单,如果您想提供一堆不同的文档选项,请执行其他操作。
如果你真的想做你所描述的,我建议你使用标签来分隔文档字符串中的部分。像这样:
def foo(bar, baz):
"""Function foo()
* Summary:
Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them.
* Developers:
When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.
* Testers:
When you test foo, be sure to try negative values for baz.
"""
pass # code would go here
然后你可以很容易地将你的字符串分割成块,当用户选择一个菜单项时,只显示适当的块。
s = foo.__doc__ # s now refers to the docstring
lst = s.split("\n* ")
section = [section for section in lst if section.startswith("Developers")][0]
print(section) # prints the "Developers" section
这样,当您在交互式 Python shell 中工作时,您可以说“help(foo)”,您将看到所有的文档字符串。而且,您并没有改变 Python 的基本部分的基本行为,这会吓坏其他试图研究您的代码的人。
您还可以做一些更简单的事情:只需为不同目的制作一个包含文档字符串的大型全局字典,然后从源代码中为每个新事物更新它。
doc_developers = {} doc_testers = {}
def foo(bar, baz):
"""Function foo()
Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them."
pass # code goes here
doc_developers["foo"] = "When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests."
doc_testers["foo"] = "When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests."
我最不喜欢的一点是,如果您更改函数 foo 的名称,则需要在多个位置进行更改:实际更改一次,def
每个字典更新行更改一次。但是你可以通过编写一个函数来解决这个问题:
def doc_dict = {} # this will be a dict of dicts
doc_dict["developers"] = {}
doc_dict["testers"] = {}
def doc_update(fn, d):
name = fn.__name__
for key, value in d.items():
doc_dict[key][name] = value
def foo(bar, baz):
"""Function foo()
Function foo() handles all your foo-ish needs. You pass in a bar and a baz and it foos them."
pass # code goes here
d = { "developers": "When you change foo(), be sure you don't add any global variables, and don't forget to run the unit tests.",
"testers": " When you test foo, be sure to try negative values for baz."}
doc_update(foo, d)
可能有一种方法可以将 doc_update() 变成装饰器,但我现在没时间了。