1
我使用Google风格的文档字符串与sphinx.ext.autodoc自动生成我的函数的文档,并确保它们在代码中正确自我记录。在同一函数中记录不同的参数可能性
我有一个函数def myfunc(id=None, size=None, hash=None)
,基于id
或size + hash
返回信息。如果我们有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
但是,在这种情况下,单一的功能会如果可能的话,这是首选,因为该函数是绑定到使用单个函数的另一个API。
这告诉参数是否是可选的,但如果我的情况适用于这个例子,** param1 **将会变成可选的,如果** param2 **被使用。 – toucanb
这个用法有点难以遵循。如果您正在设计一个采用可选参数的函数,那么可以理解它恰好是*那*。如果这些参数对需要一起给出,你可能想把它们放在一个命名的元组或其他有用的结构中。这可能是更好的设计选择。 – idjaw
个人而言,我认为你应该坚持为了清晰和明确的目的而分解你的函数。此外,使文档更易于编写。 – idjaw