user3541631
user3541631

Reputation: 4008

Python: Create a try except general purpose function

For a parsing script I need to use in many places try except blocks. I thought I can use a general purpose function which use as the parameter the expression that need to be evaluated.

I cannot used the expression directly as a parameter because it can trow an error before entering in try except block:

def exception(a, nr_repeat=5):
if nr_repeat != 0:
    try:
        a
        nr_repeat = 0
    except ExceptionType:
        exception(a, nr_repeat-1)

So, I start passing a , the expression to evaluate as a string, and use exec:

def exception(a, nr_repeat=5):
 if nr_repeat != 0:
    try:
        exec(a)
        nr_repeat = 0
    except ExceptionEx:
        exception(a, nr_repeat-1)

which is working if the expression doesn't use variables. If it uses variables, even if I pass then to the function is not working.

def exception(a, nr_repeat=5,*args):
 if nr_repeat != 0:
    try:
        exec(a)
        nr_repeat = 0
    except ExceptionEx:
        exception(a, nr_repeat-1)

function:

exception("print('blue)") - working
exception("data.split('/')") - not working

ExceptionEx is just a placeholder for different exceptions

Upvotes: 0

Views: 778

Answers (1)

Maksim Solovjov
Maksim Solovjov

Reputation: 3157

Have you tried passing in a lambda function?

exception(lambda: data.split('/'))

and inside of your function:

def exception(a, nr_repeat=5):
if nr_repeat != 0:
    try:
        a()
        nr_repeat = 0
    except ExceptionType:
        exception(a, nr_repeat-1)

The lambda will not be evaluated until you call it.

Upvotes: 4

Related Questions