我正在使用 python 3.1。
是否可以为单个模块或函数创建超过 1 个文档字符串?我正在创建一个程序,并且打算拥有多个文档字符串,每个文档字符串都有一个类别。我打算向其他人提供该程序,以便他们可以使用它,并且为了让程序员和非程序员都轻松使用它,我在程序本身中放置了对文档字符串的引用。
更具体地说,我在程序/模块中有一个菜单作为界面,其中一个选项将允许访问模块文档字符串以获取程序文档。因此,如果可能的话,我想制作多个文档字符串来对不同类型的文档进行分类。因此,如果用户想查看文档的某些部分,会更容易。
例如。第一个文档字符串包含有关如何使用该程序的说明。第二个文档字符串包含有关程序的一部分如何工作的信息。第三个文档字符串包含有关其他部分如何工作的信息。ETC。
这可能吗?如果是这样,你如何引用它们?
更新:添加了评论。
我最初的想法是实际上拥有多个文档字符串,其含义如下:
def foo():
"""docstring1: blah blah blah"""
"""docstring2: blah blah blah"""
pass # Insert code here
Run Code Online (Sandbox Code Playgroud)
然后我可以使用一些代码来引用每个文档字符串。那么,我猜这是不可能的?
我不建议尝试使用文档字符串做一些复杂的事情。最好保持文档字符串简单,如果您想提供一堆不同的文档选项,请执行其他操作。
如果您确实想做您所描述的事情,我建议您使用标签来分隔文档字符串中的部分。就像这样:
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
Run Code Online (Sandbox Code Playgroud)
然后,您可以很容易地将字符串分割成块,并且当用户选择菜单项时,仅显示适当的块。
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
Run Code Online (Sandbox Code Playgroud)
这样,当您在交互式 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."
Run Code Online (Sandbox Code Playgroud)
我最不喜欢的一点是,如果更改函数 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)
Run Code Online (Sandbox Code Playgroud)
可能有一种方法可以将 doc_update() 变成装饰器,但我现在没时间。
归档时间: |
|
查看次数: |
3225 次 |
最近记录: |