Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 250
Eric H. Avatar asked May 16 '18 12:05

Eric H.


People also ask

How do you use docstrings in Python?

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.

What is used while writing docstrings?

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.


1 Answers

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
like image 167
Haleemur Ali Avatar answered Oct 30 '22 16:10

Haleemur Ali