Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Error Resume Next in Python

Snippet 1

do_magic() # Throws exception, doesn't execute do_foo and do_bar
do_foo()
do_bar()

Snippet 2

try:
    do_magic() # Doesn't throw exception, doesn't execute do_foo and do_bar
    do_foo() 
    do_bar()
except:
    pass

Snippet 3

try: do_magic(); except: pass
try: do_foo()  ; except: pass
try: do_bar()  ; except: pass

Is there a way to write code snippet 3 elegantly?

  • if do_magic() fails or not, do_foo() and do_bar() should be executed.
  • if do_foo() fails or not, do_bar() should be executed.

In Basic/Visual Basic/VBS, there's a statement called On Error Resume Next which does this.

like image 461
Elmo Avatar asked Sep 26 '14 12:09

Elmo


People also ask

What does On error Resume Next do?

On Error Resume Next Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred and execution continues. Use this form rather than On Error GoTo when accessing objects.

How do you continue a loop if error in Python?

The SyntaxError: continue not properly in loop error is raised when you try to use a continue statement outside of a for loop or a while loop. To fix this error, enclose any continue statements in your code inside a loop.


3 Answers

In Python 3.4 onwards, you can use contextlib.suppress:

from contextlib import suppress

with suppress(Exception): # or, better, a more specific error (or errors)
    do_magic()
with suppress(Exception):
    do_foo()
with suppress(Exception):
    do_bar()

Alternatively, fuckit.

like image 88
jonrsharpe Avatar answered Sep 19 '22 08:09

jonrsharpe


If all three functions accept same number of parameters:

for f in (do_magic, do_foo, do_bar):
    try:
        f()
    except:
        pass

Otherwise, wrap the function call with lambda.

for f in (do_magic, lambda: do_foo(arg1, arg2)):
    try:
        f()
    except:
        pass
like image 45
falsetru Avatar answered Sep 22 '22 08:09

falsetru


If there are no parameters...

funcs = do_magic, do_foo, do_bar

for func in funcs:
    try:
        func()
    except:
        continue
like image 40
Keith Aymar Avatar answered Sep 20 '22 08:09

Keith Aymar