2014-11-03 113 views
6

爲字典參數添加文檔字符串的建議方式是什麼?我可以看到多行DOC文本字符串示例here如何爲字典添加python文檔字符串

我需要將輸入參數記錄到文檔字符串中的函數。如果它是一個簡單的變量,我可以使用類似:

def func2(a=x, b = y): 
""" fun2 takes two integers 

Keyword arguments: 
a -- refers to age (default 18) 
b -- refers to experience (default 0) 
""" 

如果我們有dict作爲輸入參數傳遞給函數:

def func3(**kwargs): 
    """ takes dictionary as input 

     <Here how to explain them - Is it like?> 
     kwargs['key1'] -- takes value1 

     <or simply> 
     key1 -- takes value1 
     """ 
+4

你能請解釋一下你的意思?你的意思是如何記錄一個應該是字典的參數? – jonrsharpe 2014-11-03 10:46:38

+0

是的,如何記錄一個字典的參數。 – 2014-11-03 12:08:34

回答

10

我一般採用Google docstring style,所以一本字典參數會是什麼樣子:

def func(a_dict): 
    """Some function to do something to a dictionary. 

    Args: 
     a_dict (dict of str: int): Some mapping, I guess? 

    """ 
    ... 

這需要**kwargs(注一項功能:這是相當與具有字典參數相同),將如下所示:

def func(**kwargs): 
    """Some function to do stuff to arbitrary keyword arguments. 

    Args: 
     **kwargs: Arbitrary keyword arguments. 

    """ 
    ... 

如果存在應該存在的特定參數(例如,你的key1),它們應該是分開的,而不是捲成**kwargs


在Python 3.x中,你也可以使用function annotations

def func(a_dict: dict): 
    """Some function to do something to a dictionary.""" 
    ... 

通過Python 3.5,你可以更加明確的使用typing

from typing import Mapping 

def func(a_dict: Mapping[str, int]): 
    """Some function to do something to a dictionary.""" 
    ... 
+0

謝謝,現在明白了。 – 2014-11-03 12:19:53

相關問題