格式化字典的python文档字符串 [英] Formatting python docstrings for dicts
问题描述
为字典参数添加docstring的推荐方法是什么?我可以在此处看到多个行文档字符串示例.
What's the recommended way of adding a docstring for a dictionary parameter? I can see multiple line docstring examples here.
我需要在文档字符串中记录函数的输入参数.如果这是一个简单的变量,我可以使用类似的东西:
I need to document the input arguments to a function in the docstring. If it's a simple variable, I can use something like:
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
作为输入参数传递给函数:
If we have dict
passed as input argument to function:
def func3(**kwargs):
""" takes dictionary as input
<Here how to explain them - Is it like?>
kwargs['key1'] -- takes value1
<or simply>
key1 -- takes value1
"""
推荐答案
I generally use the Google docstring style, so a dictionary parameter would look like:
def func(a_dict):
"""Some function to do something to a dictionary.
Args:
a_dict (dict of str: int): Some mapping, I guess?
"""
...
采用**kwargs
的函数(请注意:这与具有字典参数的不完全相同),看起来像是:
A function that takes **kwargs
(note: this is not quite the same as having a dictionary parameter), would look like:
def func(**kwargs):
"""Some function to do stuff to arbitrary keyword arguments.
Args:
**kwargs: Arbitrary keyword arguments.
Keyword Args:
<kwarg_name> int: A description
<kwarg_name_2> str: Another description
<...>
"""
...
如果要显示某些特定参数(例如您的key1
),则应将它们分开,而不是放入**kwargs
中.
If there are specific parameters that should be present (e.g. your key1
), they should be separate, not rolled into **kwargs
.
在Python 3.x中,您还可以使用功能注释 :
In Python 3.x, you can also use function annotations:
def func(a_dict: dict):
"""Some function to do something to a dictionary."""
...
在Python 3.5中,您可以使用 typing
:
From Python 3.5, you can be even more explicit using typing
:
from typing import Mapping
def func(a_dict: Mapping[str, int]):
"""Some function to do something to a dictionary."""
...
这篇关于格式化字典的python文档字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!