[英]Editing __doc__ within a flat method?
我正在嘗試圍繞我編寫的api做一個超薄的cli包裝器。 好像__doc__
dunder屬性是在導入時設置的。
>>> def foo():
... """
... doc
... """
... pass
...
>>> foo.__doc__
'\n\tdoc\n\t'
我發現我可以在方法中更改__doc__
>>> def foo():
... foo.__doc__ = "new doc"
...
>>> foo.__doc__
>>> foo()
>>> foo.__doc__
'new doc'
但這需要運行該方法。
我正在編寫一個單擊工具,這允許file.py --help
打印該文檔。 但是,因為這是一個薄包裝器,所以最好將__doc__
編輯為與doc內部調用的方法相同。
API.py
class FOO:
def bar():
"""
Some long doc string
"""
pass
cli.py
import click
import API
@click.command()
def hello():
"""
not what I want
"""
hello.__doc__ = API.FOO.bar.__doc__
API.FOO.bar()
if __name__ == '__main__':
print(hello.__doc__)
hello()
print(API.FOO.bar.__doc__)
運行pyhton3.6 cli.py
時出現以下信息...
not what I want
Some long doc string
當我運行python3.6 cli.py --help
Usage: cli.py [OPTIONS]
not what I want
Options:
--help Show this message and exit.
有什么方法可以將來自導入方法的doc字符串注入到click方法中? 裝飾器也許在導入時解析,但是我不確定該怎么做。 謝謝。
如果將對doc的更改實現為函數的修飾符,它將在導入時運行。
def change_doc(function):
function.__doc__="my text"
return function
因此,一般的想法是您希望能夠使用API.FOO.bar
並API.FOO.bar
創建一個命名包裝。 沒問題,盡管需要一些開箱即用的思維。 這里的關鍵思想是要理解裝飾器也可以用作普通函數,將一個函數轉換為另一個函數:
def wrap_api(method):
result = click.command(method)
result.__doc__ = method.__doc__
return method
現在我們可以創建包裝器了:
hello = wrap_api(API.FOO.bar)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.