mercredi 27 décembre 2017

Avoid repetitive try/except in python

I have several functions (f, g, o) that have arg1 as input.

arg1 is positif, mandatory and located in different position:

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

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

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

In case arg1 is negatif I raise an exception:

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

To avoid repeat the try/except statements on all functions:

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

I investigated the idea of creating a decorator.

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)

However, this solution force me to use arg1 as a keyword argument (arg1=3) and seems overkilling.

I have noticed a few response in previous post with the usage of the contextmanager.

However, the contextmanager from what I read will re-raise the exception so it does not solve my problem.

Could you please tell me what is the righ approach ?

Regards,

Aucun commentaire:

Enregistrer un commentaire