Skip to main content
 首页 » 编程设计

python之记录同一函数的不同参数可能性

2025年02月15日9haluo1

我使用 Google 风格的文档字符串和 sphinx.ext.autodoc 来自动为我的函数生成文档,并确保它们在代码中正确地 self 记录。

我有一个函数 def myfunc(id=None, size=None, hash=None) 返回基于 id 或 的信息大小 + 哈希。如果我们将 id 作为参数,则不需要 size 和 hash,如果我们有 size 和 hash 作为参数,则不需要 id。

使用 sphinx,可以指定一个可选参数,但在这种情况下,我们不知道什么是必需的,什么是可选的。这是一个例子:

def get_file(id=0, size=0, hash="") 
    """ 
    Get file metadata. 
 
    Args: 
        id (int): id of the file. 
        size (int): file size in bytes. 
        hash (str): md5 hash of file. 
 
    Returns: 
        file_data (str): metadata information about the file. 
    """ 
    if id: 
        # Get file with id. 
        ... 
    elif size and hash: 
        # Get file with size and hash. 
        ... 
    else: 
        # Bad arguments, handle error. 
        ... 
 
    return file_data 

问题是:如何判断文档字符串中需要哪些参数?

你可以很容易地争辩说函数本身就是问题所在,即使结果相同,两个参数对也应该在不同的函数中:

def get_file_by_id(id) 
    """ 
    Get file metadata from id. 
 
    Args: 
        id (int): id of the file. 
 
    Returns: 
        file_data (str): metadata information about the file. 
    """ 
 
    # Get file with id. 
    ... 
 
    return file_data 
 
def get_file_by_hash(size, hash) 
    """ 
    Get file metadata from hash. 
 
    Args: 
        size (int): file size in bytes. 
        hash (str): md5 hash of file. 
 
    Returns: 
        file_data (str): metadata information about the file. 
    """ 
 
    # Get file with hash+size. 
    ... 
 
    return file_data 

但在这种情况下,如果可能的话,单个函数将是首选,因为该函数绑定(bind)到另一个使用单个函数的 API。

请您参考如下方法:

根据文档,here ,下面的示例方法定义:

def module_level_function(param1, param2=None, *args, **kwargs): 

文档字符串定义为:

Args: 
    param1 (int): The first parameter. 
    param2 (:obj:`str`, optional): The second parameter. Defaults to None. 
        Second line of description should be indented. 
    *args: Variable length argument list. 
    **kwargs: Arbitrary keyword arguments. 

因此,您明确说明了可选的,否则将被理解为强制参数。