Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning from a function immediately after calling another function

Function calculate_attribute does not return a value; it only works through side effects.

Often within that function I have to write these few lines:

print('some message')
set_attribute(value)
return

So I decided to put this into a different function:

def report_and_set(value, message):
  print(message)
  set_attribute(value)

Is it ok to now do the following:

   def calculate_attribute(params):
     #...
     if something:
       return report_and_set(value, message)
     #...
     if another_condition:
       return report_and_set(value, message)
     #...     

It feels kinda weird to write this since report_and_set has no return value. But if I don't, I'd have to repeatedly type return after every call to report_and_set.

like image 800
max Avatar asked Aug 27 '26 06:08

max


2 Answers

Well, you have to type return every time either way. I'm not sure what you gain (or lose) by doing it the way you suggest, especially since

return

is effectively the same as

return None

But I wonder why you have these empty return statements in the function at all. Is it necessary? There might be a more elegant or easier-to-read way to handle the flow of control in this function. A random return in the middle of a function can be easy to miss.

More abstractly speaking, counting return statements is a good rough heuristic for measuring function complexity; most of the time, more returns implies more cyclomatic complexity. There's even a school of thought that insists on using return only once in any given function, based on the oft-cited principle of "single entry, single exit." In fact, I think "single entry, single exit" is different from "one return only," which to me seems quite strict, and onerous at times. (For more, see this post, which suggests that "one return only" is based on a misunderstanding of SESE). But the general principle that fewer return statements is better still seems like a good one to me.

like image 134
senderle Avatar answered Aug 29 '26 20:08

senderle


Many programmers, myself included, prefer a single return per function.

Occasionally, I may insert a return in the first few lines of a function to bail if some sanity check fails.

I wouldn't in this case.

In this case, I would simply do...

   def calculate_attribute(params):
     #...
     if something:
       report_and_set(value, message)
     #...
     elif another_condition:
       report_and_set(value, message)
     #...     

But also consider the Single Responsibility Principle (it applies equally to functions and classes). If your function is long and contains lots of conditional function invocations, it's probably time to refactor!

like image 33
Johnsyweb Avatar answered Aug 29 '26 22:08

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!