【发布时间】:2017-06-16 02:18:07
【问题描述】:
我正在使用带有 sphinx.ext.autodoc 的 Google 样式的文档字符串来自动为我的函数生成文档,并确保它们在代码中正确地自我记录。
我有一个函数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 的绑定。
【问题讨论】:
标签: python python-sphinx docstring sphinx-napoleon