I'm using Google-style docstrings with sphinx.ext.autodoc to automatically generate documentation for my functions, and make sure they are properly self-documented in the code.
I have a function def myfunc(id=None, size=None, hash=None)
that returns information based on id
or size + hash
. If we have id
as an argument, size
and hash
are not needed, if we have size
and hash
as arguments, then id
isn't needed.
With sphinx, it is possible to specify an optional argument, but in this case we don't know what will be mandatory and what will be optional. Here's an example:
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
The question is: how to tell what arguments are necessary in the docstring?
You could easily argue that the function itself is the issue, that both argument pairs should be in separate functions even if the result is the same:
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
But in this case a single function would be preferred if possible, since the function is a binding to another API that uses a single function.