问题
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