为字典格式化Python文档字符串
给字典参数添加文档字符串的推荐方法是什么呢?我看到有很多多行文档字符串的例子,可以在这里找到。
我需要在文档字符串中记录函数的输入参数。如果是简单的变量,我可以用类似这样的方式:
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
作为输入参数传递给函数:
def func3(**kwargs):
""" takes dictionary as input
<Here how to explain them - Is it like?>
kwargs['key1'] -- takes value1
<or simply>
key1 -- takes value1
"""
2 个回答
4
对于使用PyCharm的朋友们:你可以在以下位置设置默认的文档字符串格式:
Preferences -> Tools -> Python Integrated Tools -> Docstrings
从版本2019
开始,允许的选项有:Plain(普通文本)、Epytext、reStructuredText、NumPy、Google。这个功能会在你输入三个双引号"
并按下enter
键后,自动添加一个文档字符串的框架。
23
我一般使用谷歌文档字符串风格,所以一个字典类型的参数看起来会是这样的:
def func(a_dict):
"""Some function to do something to a dictionary.
Args:
a_dict (dict of str: int): Some mapping, I guess?
"""
...
一个接受**kwargs
的函数(注意:这和有一个字典参数并不完全相同)看起来会是这样的:
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
里面。
在Python 3.x中,你还可以使用函数注解:
def func(a_dict: dict):
"""Some function to do something to a dictionary."""
...
从Python 3.5开始,你可以更明确地使用typing
:
from typing import Mapping
def func(a_dict: Mapping[str, int]):
"""Some function to do something to a dictionary."""
...