NIlesh Sharma
NIlesh Sharma

Reputation: 5665

number of returns in a function

Is there any harm if we use many return positions in a python function ? Like suppose if I want to return a function if value is not 3 and value is not None (Just a scenario). So it can be done in so many ways like

def return_value(value):
 if value != 3:
  return None
 if value is not None:
  return None
 if value != 'string':
  return None

or It can be done like this:

def return_value(value):
 if value != 3 or value is not None or value !='string':
  return None

Again, I would like to use second way of writing code only, but just for a doubt I am asking having many returns somehow affects the performance of function or not ?

Upvotes: 2

Views: 107

Answers (2)

Nick Burns
Nick Burns

Reputation: 983

It seems a very interesting scenario that you have used above, but conceptually there is no issue with multiple return points in a function.

In a real scenario, it is likely that your test conditions will be logically similar, and that grouping them together, as in your second example, will make good logical sense and keep your code easy to read.

Cheers

Upvotes: 4

Lennart Regebro
Lennart Regebro

Reputation: 172377

No, there is no harm in having many returns.

That said, I would in this case definitely go with the second version. The first is harder to read, and slower (although optimizing for speed without a benchmark is always premature). It is not the many returns that make its lower though, but the many ifs.

Upvotes: 5

Related Questions