2015-08-22 38 views
2

我試圖做一個文檔字符串,將接受替代字段如下我可以格式化文檔字符串中python3

def run_tests(args): 
    """run tests on methods in {0} 

    usage: {0} --tests 
    """.format(__file__) 
    pass 

,但是當我在解釋器中運行help(run_tests),我沒有得到的文檔字符串。如果我刪除{}和.format(),則文檔字符串按預期返回。

我想看到的輸出是這樣的:

Help on function run_tests in module myfile: 

run_tests(args) 
    runs tests on methods in myfile.py 

    usage: myfile.py --tests 

有沒有辦法在python3做到這一點?

+0

既不適用於Python的2;請參閱https://stackoverflow.com/questions/36705130/python-docstrings-templated for solution – abukaj

回答

0

基於Python docstrings templated我定製了以下裝飾:

def _formatDostring(*args, **kwargs): 
    def decorator(o): 
     o.__doc__ = o.__doc__.format(*args, **kwargs) 
     return o 

    return decorator 

@_formatDostring(__file__=__file__) 
def run_tests(args): 
    """run tests on methods in {__file__} 

    usage: {__file__} --tests 
    """ 
    pass