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 ?
Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Python documentation string or commonly known as docstring, is a string literal, and it is used in the class, module, function, or method definition. Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With