Removal of return keyword in the case of one line functions

removal of repetitive code that is not useful

for example,

def f(x): return x*2

should be made

def f(x): x*2

I’ve seen this in languages like CoffeeScript and I can tell you this is a horrible idea. I often ended up returning things I never intended to, just because my last function call returned something. Special casing one line functions (which, btw, are forbidden by PEP 8) would make this a non-obvious effect for programmers who had not read about this specific feature.


one of the aim should also be to reduce the number of lines of code written to do a particular task, one line functions with no return keyword are definitely something people would get used to pretty soon.

How does the lack of a return statement reduce the number of lines in a single line function?

Lambdas are probably a better fit here, yes?

1 Like

That’s actually not an aim of Python. From the Zen of Python, “Explicit is better than implicit”, “Readability counts”, “There should be one-- and preferably only one --obvious way to do it”, etc. It’s okay if something takes longer than is potentially necessary as readability is extremely important.

Plus this suggestion is not backwards-compatible without fixing a bug or offering a new type of programming that wasn’t possible before, so this simply isn’t possible to change.


For better or worse, Python maintains a clear syntactic division between “statements” and “expressions”. lambda expression contains an expression; def statement contains statements, and requires explicit return, if you want a return value. def without return is also meaningful, for “void” procedures that are called for their side effects.
Single-line def is still a statement; redefining it’s meaning just because it’s compressed onto one line would blur this statement/expression and be very confusing :-1:

Brett’s point that this proposal would break compatibility is correct too.

But this style is already possible, though quite rarely used:

import math
double = lambda x: 2 * x
square = lambda x: x**2
compose = lambda f, g: lambda x: g(f(x))
log_sandwich = lambda f: compose(math.log, compose(f, math.exp))
indirect_square = log_sandwich(double)
approx_derivative = lambda f, dx=1e-9: lambda x: (f(x+dx) - f(x)) / dx
approx_double = approx_derivative(square)

I suspect when people do use it, it’s not just for brevity but also for uniformity emphasizing the “functions are values” angle — note how this creates a function in all assignments but 2 of these don’t involve any def/lambda syntax. In this frame of mind, that doesn’t matter, so it’s pleasant that all defined names are on the left; this uniformity would be harmed by using def.
(This is of course a stylistic choice that’s not always appropriate.)

1 Like