basic_math-checkpoint


Basic Math: Examples of decorators

A simple function:


In [30]:
def add(a, b):
    """add() adds things"""
    return a + b

In [31]:
add(3,4)


Out[31]:
7

But what if we'd like to log when it's called ?


In [32]:
def logged_add(a, b):
    print '### %s(%r, %r)' % ('add', a, b)
    result = add(a, b)
    print '### %s(%r, %r) --> %r' % ('add', a, b, result)
    return result

In [33]:
logged_add(3,4)


### add(3, 4)
### add(3, 4) --> 7
Out[33]:
7

You could change all calls to this... bleh

( Particularly if you have multple functions you want logged versions of. )

So make a "wrapper function" that will created a logged version of an arbitrary function:


In [34]:
def logged(func):
    def wrapper(a, b):
        print '### %s(%r, %r)' % (func.func_name, a, b)
        result = func(a, b)
        print '### %s(%r, %r) --> %r' % (func.func_name, a, b, result)
        return result
    return wrapper

And use it for add:


In [35]:
add = logged(add)

In [36]:
add(3,4)


### add(3, 4)
### add(3, 4) --> 7
Out[36]:
7

And make it more generic (arbitrary number of arguments)


In [37]:
def logged(func):
    def wrapper(*args):
        print '### %s(%s)' % (func.func_name, args)
        result = func(*args)
        print '### %s(%s) --> %r' % (func.func_name, args, result)
        return result
    return wrapper

In [38]:
def add(a, b):
    """add() adds things"""
    return a + b
add = logged(add)

In [39]:
add(3,4)


### add((3, 4))
### add((3, 4)) --> 7
Out[39]:
7

And a couple more:


In [40]:
def subtract(a, b):
    """subtract() subtracts two things"""
    return a - b
subtract = logged(subtract)

def even(a):
    """even() returns True if the value is even"""
    return a % 2 == 0
even = logged(even)

And use them...


In [41]:
add(1, 1)


### add((1, 1))
### add((1, 1)) --> 2
Out[41]:
2

In [42]:
add(2, 2)


### add((2, 2))
### add((2, 2)) --> 4
Out[42]:
4

In [43]:
subtract(2, 1)


### subtract((2, 1))
### subtract((2, 1)) --> 1
Out[43]:
1

In [44]:
even(42)


### even((42,))
### even((42,)) --> True
Out[44]:
True

In [45]:
even(43)


### even((43,))
### even((43,)) --> False
Out[45]:
False

In [ ]: