Tuesday, May 26, 2015

Decorators in Python

In Python Decorators are functions of functions. It is a wrapper function that wraps a regular function to modify its results.  
For example, say you have a function to capitalize the first letter of names. Now you want to add another function on top of this to include the title (Mr/Ms) depending upon the gender. This can be achieved by defining a decorator function to add the title. 

Decorator Function to add the title (Mr/Ms) based on gender:
def Title(func):
  def new(*args, **kwds):
    if kwds['gender'] == 'male': return ("Mr "+func(*args, **kwds))
    elif kwds['gender'] == 'female': return ("Ms "+func(*args, **kwds))
    else: return func(*args, **kwds)
  return new

Regular function to capitalize the first letter with decorator:
def Capitalize(name,gender=''):
  return name.title()

Now call the regular function as below:
Capitalize('john travolta',gender='male')
result >>> 'Mr John Travolta'

Capitalize('catherine zeta jones',gender='female')
result >>> 'Ms Catherine Zeta Jones'