What is the best way in python to write docstrings for lambda functions?

让人想犯罪 __ 提交于 2021-02-20 18:52:26

问题


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 ...
  """
  ...

But what is the best way to comment a lambda function ? I hesitate between :

# This function does ...
func2 = lambda x: ...

or :

func2 = lambda x: ...
""" This function does ... """

or else ?


回答1:


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.

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.

Quoting directly from pep-8

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x

No:

f = lambda x: 2*x


来源:https://stackoverflow.com/questions/50370917/what-is-the-best-way-in-python-to-write-docstrings-for-lambda-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!