简体   繁体   English

python多重赋值,可能有例外

[英]python multiple assignment with possible exceptions

I am using python 3.x I have lot of variables, and lot of functions.我正在使用 python 3.x 我有很多变量和很多功能。 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.这些函数可能会抛出异常,在这种情况下我需要返回 None。 I would like to write a function that do this assignment.我想写一个函数来完成这个任务。

assign(x1,f1).

Any ideas how to realize it.任何想法如何实现它。

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)

You can use decorators.您可以使用装饰器。 The decorator catches the exception and returns None.装饰器捕获异常并返回 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

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.可能可以进一步缩短和优化,但这个想法应该可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM