Try to eliminate an 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   
+4
source share
2 answers

Yes it is.

Assigning the first and then returning doesn't matter when it comes to catching exceptions. The appointment of aaa completely redundant.

+11
source

Yes, it does not matter. Your possible source of exception is the foo () function, and you still call it in both programs. Assigning its output to aaa will not change anything, since an exception will occur when foo () is called not at the time of the assignment (which is still in the try block).

+2
source

Source: https://habr.com/ru/post/1491113/


All Articles