[Tutor] Named function in a single line

Alan Gauld alan.gauld at yahoo.co.uk
Thu Sep 10 16:18:49 EDT 2020


On 10/09/2020 18:34, Manprit Singh wrote:

> def multiply(a, b) : return a * b
> 
> PEP 8 allows us to write such small functions in a single line ?

Others have addressed the PEP8 issue, I'll offer a slightly different
take on why you might do this.

When we define a function we are, in computer science terms, creating
a lambda expression. We can do this explicitly in Python (and must do
so explicitly in some dialects of Lisp) with:

multiply = lambda a,b: a*b

Which is identical to the function definition above and is used in
the same way:

print(multiply(4,7))  # prints 28

The lambda form simply reflects the CS theory. But most non CS
folks don't like (or understand) lambdas so the single line
definition combines the terseness of the lambda style with the
familiar def syntax.

For multi line definition lambda can't be used since it only
works (in python) for single expressions. You can't have loops
or sequences etc. in a Python lambda.

Don't read this as a recommendation for the lambda style, it's not.
It's just an observation on the philosophy behind short function
definitions.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list