4

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   
Thomash
  • 6,339
  • 1
  • 30
  • 50
dola
  • 201
  • 4
  • 9

2 Answers2

11

Yes, it is.

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yup - if an exception occurs in the example the name binding never occurs anyway - so not even the chance of weird things happening with ref counts – Jon Clements Jul 12 '13 at 12:31
2

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).

Aleksander Lidtke
  • 2,876
  • 4
  • 29
  • 41