在python中为lambda函数编写文档字符串的最佳方法是什么? [英] What is the best way in python to write docstrings for lambda functions?
问题描述
我通常使用带有"的多行文档字符串注释我的函数,如中所述: https://www.python.org/dev/peps/pep-0257/
I usually comment my functions using multi-line docstrings with """, as mentioned in : https://www.python.org/dev/peps/pep-0257/
def func1(x):
"""
This function does ...
"""
...
但是注释lambda函数的最佳方法是什么?我犹豫之间:
But what is the best way to comment a lambda function ? I hesitate between :
# This function does ...
func2 = lambda x: ...
或:
func2 = lambda x: ...
""" This function does ... """
否则?
推荐答案
tbh,甚至对一个变量分配一个lambda对我来说似乎都不是Python的.如果需要名称,请将其定义为常规函数. lambda函数与常规函数之间的区别在于,后者具有__name__
属性和显式的return语句.
tbh, even assigning a lambda to a variable seems unpythonic to me. if it needs a name, define it as a regular function. The difference between a lambda function and a regular function is that the latter has a __name__
attribute and an explicit return statement.
如果必须将文档字符串添加到lambda,请执行以下操作:
if you must add a docstring to a lambda, do it like this:
f = lambda x: x + 1
f.__doc__ = """adds 1 to input-arg"""
help(f)
# outputs the following:
help(f)
Help on function <lambda> in module __main__:
<lambda> lambda x
adds 1 to arg
这样,文档实际上可以作为函数文档字符串提供给解释器.
This way, the documentation is actually available to the interpreter as a function docstring.
直接从 pep-8 报价
始终使用def语句代替将lambda表达式直接绑定到标识符的赋值语句.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
是:
def f(x): return 2*x
否:
f = lambda x: 2*x
这篇关于在python中为lambda函数编写文档字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!