Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try except unnecessary step

Is it always safe to use hello2 instead of hello1 ?

def hello1():
    try:
        aaa = foo()
        return aaa
    except baz:
        return None   

def hello2():
    try:
        return foo()
    except baz:
        return None   
like image 644
dola Avatar asked Dec 11 '22 13:12

dola


2 Answers

Yes, it is.

Assigning first then returning makes no difference when it comes to catching exceptions. The assignment to aaa is entirely redundant.

like image 159
Martijn Pieters Avatar answered Jan 01 '23 02:01

Martijn Pieters


Yes, it makes no difference at all. Your possible source of an exception is the foo() function and you call it anyway in both programs. Assigning its output to aaa will not change anything, since the exception will originate when calling foo() not during the assignment (which is located in try block anyway).

like image 29
Aleksander Lidtke Avatar answered Jan 01 '23 01:01

Aleksander Lidtke