避免在python中重复尝试/除外

时间:2017-12-27 09:51:12

标签: python design-patterns python-decorators

我有几个以f作为输入的函数(goarg1)。

arg1是positif,强制性的,位于不同的位置:

def f(a, b, arg1):
    print(arg1)

def g(c, arg1):
    print(arg1)

def o(arg1, d, 2):
    print(arg1)

如果arg1是negatif,我会引发异常:

def is_positif(a):
    if a < 0:
        raise ValueError('arg1 should be positif)

为避免重复所有函数的try/except语句:

def f(a, b, arg1):
    try:
        is_positif(arg1)
        print(arg1)
    except ValueError as err:
        print(err)

我研究了创建装饰器的想法。

from functools import wraps

def valid_arg(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            is_positif(kwargs['arg1'])
            func(*args, **kwargs)
        except ValueError as err:
            print(err)
    return wrapper

def is_positif(x):
    if x < 0:
        raise ValueError("arg1 should be positif")

@valid_arg
def f(a, b, arg1):
    print(arg1)

if __name__ == '__main__':
    f(1, 2, arg1=3)

但是,此解决方案迫使我使用arg1作为关键字参数(arg1=3)并且似乎过度使用。

我在前一篇文章中注意到了一些使用contextmanager的回复。

但是,我读到的contextmanager会重新引发异常,因此无法解决我的问题。

你能告诉我这种方法是什么吗?

此致

1 个答案:

答案 0 :(得分:1)

为了避免在所有函数上重复try / except语句,您可以将“有用”代码包装到单个try-catch中,并在其中打印有用的错误消息。此外,您可以为您的案例创建自定义例外。

# Your custom exception
class NegativeArg1(Exception):
    pass

# Your checker
def check_positive(arg1):
    if val < 0:
        raise NegativeArg1("Your arg1 is negative!")

# Your calculation function
def f1(a, b, arg1):
    check_positive(arg1)
    # make calculations...
    c = a + b
    return c

# Your other calculation function
def f2(a, b, arg1, d, e):
    check_positive(arg1)
    # make calculations...
    c = a + b - d - e
    return c

# Your main code block:
if __name__ == '__main__':
    try:        
        r1 = f1(1, 2, arg1=3)
        r2 = f2(1, 2, arg1=-5, 6, 7)

    except NegativeArg1 as n:
        print("Oh on! You've speecified negative arg1 somethere!")
    except Exception as e:
        print("Some other exception has happened:" + str(e))