ashish14
ashish14

Reputation: 670

Which of these methods is a correct way to return in python?

I have two functions which do the same thing basically but return differently in case of exceptions. Which one is the preferred approach?

Approach 1:

def f1():
    try:
        data = some_random_function()
        return data["success"]
    except Exception as error:
        print(error)
        return "failure"

Approach 2:

def f2():
    try:
        data = some_random_function()
        return data["success"]
    except Exception as error:
        print(error)
    return "failure"

Upvotes: 1

Views: 80

Answers (4)

paradocslover
paradocslover

Reputation: 3294

Although both the approaches work the same way i.e. return data["success"] in case of an exception-free code and return "failure" otherwise, the two approaches differ in the way they convey the information :

A1- Return "failure" in case of an exception

A2- Return "failure" as a default return value.

So, it's my suggestion that you use the second approach as it is more clear and explicit.

Upvotes: 1

Shababb Karim
Shababb Karim

Reputation: 3733

Its all down to personal preferences. For me, approach 1 is much clearer than two but both are good solutions. I think its more than just individual preference, its more of the code base you are working with. If you are working with a team, look into code with similar structure, see what other's have done. A uniform codebase is much valuable than fancy code here and there.

Also, for languages like JavaScript and python, which have functional scope, I want to put forward a third option:

def f3():
    try:
        data = some_random_function()
        message = "success"
    except Exception as error:
        print(error)
        message = "failure"
    return message

Upvotes: 1

Sid
Sid

Reputation: 4995

Although both approaches are equivalent, I would recommend approach 1. It makes much clearer that 'failure' is returned only when there is an exception. Someone reading approach 2 may get a first impression that it always returns 'failure'. This is strictly from a clean code perspective.

Upvotes: 2

Stefan Becker
Stefan Becker

Reputation: 5962

As you have a generic catch-all for errors, both approaches are equivalent, because in case of an exception you'll enter the print "failure" branch.

I guess it comes down to matter of taste and maybe future maintainability, i.e. when you add more except branches to handle some errors differently, to choose approach 2.

Upvotes: 1

Related Questions