Python Notes (0.14.0)

4. Decorators

4.1. Quickstart

The following code is made of a simple division function that takes an input argument, which may be zero. In such case, the function raise a ZeroDivision exception. The decorator (check_validity) goal is to return False and not to raise any excption.

def check_validity(f):
    def wrap(*args):
        if args[0] == 0:
            return False
        return f(*args)
    return wrap

@my_decorator
def division(n):
    return 100./n

4.2. Decorator without argument for a function with arguments and optional arguments

This is exaclty the same principle as in the quick start example. Here, we added the optional arguments l=10 and therefore kargs in the decorator.

# decorator without for a function with arguments
def check_validity(f):
    """decorator without for a function with arguments

    :param f: function on which the decorator is applied

    """

    # this is the actual wrapping 
    def wrap(*args, **kargs):
        """The decorator accepts functon with arguments and optional arguments
        It return false kargs['l'] == args[0] i.e. when a division by zero 
        will be performed. Otherwise, it returns the function.

        """
        l = kargs.get('l', 0)
        if args[0] == l:
            return False
        return f(*args, **kargs)

    return wrap



@check_validity
def division(n, l=10.):
    """

    :param float n: 
    :param float l:

    return :math:`\\frac{100}{(n-l)}`
    """
    return 100./(n - l)