I think yo are a bit confused about expressions vs statements:
an expression evaluates to a value, e.g.:
x + 5
a statement does something, e.g.
`return this’
as you see, return is a staemetn, tis returns from the funtion, returning the value after it.
finally, a “ternary expression”:
x if this else that
is an expression – it evaluates to a value – in this case, either the value of x
or that
, depending on the truthiness of this
.
So:
When you write:
`return None if x > 1 else something_else
you are writing:
“terminate the function and return the value that the follwoing expressin evaluates to” – the following expression being:
None if x > 1 else something_else
so the function will alway end here, and return either None or somthing_else.
I think the confusion is that:
if this:
is a statement, whereas:
x if this else that
while using the “if” in a similar way, is an expressions.
Anyway, you haven’t posted the full twenty line, function, so hard to tell if it can be clearnly refa tors, but:
if condition1:
return this
if condition2:
return that
some_more
lines_of_code
is fine – no reason to remove lines of code just for brevity.
On the other hand, some folks think returning in the middle of a function can be bad style – it’s a bit harder to see at a glance where the function ends, so you can do:
if something:
return_value = this
elif somethign_else:
return_value = that
else:
a_bunch
more_code
...
return return_value
That way there is a dingle return, at the end of the function.
HTH,
-CHB