Journey to Master Python (WIP)

ageekymonk
2,758 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Decorators

Decorator is a syntactic sugar for higher order functions. Higher order functions take a function as input and return another function. It extends the functionality of the input function for fun and profit

For programmers print is best tool for debugging. In the example below the decorator is used to print the input and output of a function. Just adding the decorator to functions will do the job rather than going inside the function and adding a print and it is reusable.

Decorators
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def debug_input_output(f):
def wrapping_function(*args, **kwargs):
print(f'Input: {args} {kwargs}')
ret = f(*args, **kwargs)
print(f'Output: {ret}')
return ret
return wrapping_function
@debug_input_output
def addressbook(name, **details):
"""My addressbook"""
return {'name': name, **details}
addressbook('jason', age=40, address='unknown')
print(addressbook.__name__)
print(addressbook.__doc__)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

This implementataion of decorator has two problems.

  1. Name of the function is wrong
  2. Docstring is wrong.

Better Decorator using functools

Functools module provide necessary wrapper to write your own custom decorator. @wraps takes care of writing all the boiler plate code for retaining the name of the function and docstring. This is an improvement on our earlier implementataion.

Custom Decorator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from functools import wraps
import time
def timeme(f):
@wraps(f)
def wrapper(*args, **kwargs):
time1 = time.clock()
f(*args, **kwargs)
time2 = time.clock()
print(f'It took {(time2 - time1)*1000} ms to complete {f.__name__}')
return wrapper
@timeme
def myfunc():
""" My function to sleep"""
time.sleep(1)
print("Inside myfunc")
myfunc()
print(myfunc.__doc__)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content