docstring で複雑なことをしようとすることはお勧めしません。docstring をシンプルに保ち、さまざまなドキュメント オプションを利用可能にしたい場合は別のことを行うのが最善です。
説明したことを本当にやりたい場合は、タグを使用してドキュメントストリング内のセクションを区切ることをお勧めします。そのようです:
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 シェルで作業しているときに、「help(foo)」と言うと、すべての docstring が表示されます。また、Python の基本的な部分の基本的な動作を変更していないため、コードを研究しようとしている他の人を驚かせることにもなりません。
もっと単純なこともできます: さまざまな目的のために docstring の大きなグローバル ディクショナリを作成し、新しいものごとにソース コードから更新するだけです。
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
行で 1 回、辞書の更新行ごとに 1 回です。しかし、ほとんどの場合、関数を書くことでそれを修正できます:
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() をデコレータに変える方法はあると思いますが、今は時間がありません。