# Basic Math: Examples of decorators

## A simple function:

``````

In [30]:

return a + b

``````
``````

In [31]:

``````
``````

Out[31]:

7

``````

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

``````

In [32]:

print '### %s(%r, %r)' % ('add', a, b)
print '### %s(%r, %r) --> %r' % ('add', a, b, result)
return result

``````
``````

In [33]:

``````
``````

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]:

``````
``````

In [36]:

``````
``````

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]:

return a + b

``````
``````

In [39]:

``````
``````

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]:

``````
``````

Out[41]:

2

``````
``````

In [42]:

``````
``````

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 [ ]:

``````