Home > OS >  python multiple assignment with possible exceptions
python multiple assignment with possible exceptions

Time:10-23

I am using python 3.x I have lot of variables, and lot of functions. I have to assign these variables to value of functions like:

x1 = f1()
x2 = f2()
......

these functions may throw an exceptions and in this case I need to return None. I would like to write a function that do this assignment.

assign(x1,f1).

Any ideas how to realize it.

CodePudding user response:

No, assigning to a variable from within a function is not sensibly possible, but there's no need to encapsulate the assigning into that function anyway:

def safely_call(f, *args, **kwargs):
    try:
        return f(*args, **kwargs)
    except Exception:
        logging.exception('Call to %s (%s, %s) failed', f, args, kwargs)
        return None

x1 = safely_call(f1)
x2 = safely_call(f2)

CodePudding user response:

You can use decorators. The decorator catches the exception and returns None.

def exception_handler(func):
    def inner_function(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            return None
    return inner_function

@exception_handler
def myFunc(length):
    pass

CodePudding user response:

This might be something like what you want:

def f1():
    return 1/0

def f2():
    return 5

def assign(fn):
    try:
        result = fn()
    except:
        result = None
    return result
    
x1 = assign(f1)
x2 = assign(f2)
print(x1," ",x2)

Output:

None   5

Probably can be shortened further and optimized, but the idea should work.

  • Related