correct way to catch exception with Python 'with' statement

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Nov 29 00:31:31 EST 2016


On Tuesday 29 November 2016 02:18, Ganesh Pal wrote:

> On Mon, Nov 28, 2016 at 1:16 PM, Steven D'Aprano <
> steve+comp.lang.python at pearwood.info> wrote:
> 
>>
>>
>> There is no need to return True. The function either succeeds, or it
>> raises an
>> exception, so there is no need to return any value at all.
>>
>>
>  I returned True here ,because based on the result of this function , 

But the function *always* returns True, or it doesn't return at all: it raises.

Unless you have something like:

def func():
   do some work
   if condition:
      return False
   do more work
   return True

or similar, there's no point. When you write the documentation for the 
function, if it can only ever return True, then don't worry about returning 
True. Take the built-in methods as an example: dict.update either succeeds, or 
it raises an exception. It doesn't return True:

    # this is unnecessary
    flag = mydict.update(another_dict)
    if flag:
        print "update succeeded"
    else:
        print "update failed"


That cannot happen, because if the update fails, an exception is raised.

The bottom line is, since your function *only* has "return True" and doesn't 
have "return False" anywhere, there is no point to the "return True."


>  I would want to perform next steps
> 
>  Example
>                   if  create_files_append():
>                        do_somthing()
>                   else:
>                          do_next_thing()

That cannot happen. It either returns True, or it raises an exception, so the 
"else" clause will not be executed.




-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson




More information about the Python-list mailing list