Python – Decorators

A decorator provides a simplified way to pass one callable object to another (i.e a class or function).
The main benefit of decorators is that it allows you to clearly state where and what objects are being passed to each other.

Typically this can be achieved by the following.

Without Decorators

As you can see, once the functions are assigned, we pass the example function to the bold function and then assign this back to the example function object.

import sys

 def bold(funct):
    print >> sys.stderr, "adding bold tags."
    def wrapper(*args,**kwargs):
        input = str(funct(*args,**kwargs))
        return "<b>"+input+"</b>"
    return wrapper

 def h3(funct):
    print >> sys.stderr, "adding h3 tags."
    def wrapper(*args,**kwargs):
        input = str(funct(*args,**kwargs))
        return "<h3>"+input+"</h3>"
    return wrapper

 def example(*args):
    print "you entered:",str(args[0])
    return args[0]

example = bold(example)
example = h3(example)

Decorators

To perform the above but via the use of decorators the following is used. As you can see the functions are still assigned but in order to pass the functions between each other the ‘@’ character and then the function name is applied above each function.

import sys

 def bold(funct):
    print >> sys.stderr, "adding bold tags."
    def wrapper(*args,**kwargs):
        input = str(funct(*args,**kwargs))
        return "<b>"+input+"</b>"
    return wrapper

 def h3(funct):
    print >> sys.stderr, "adding h3 tags."
    def wrapper(*args,**kwargs):
        input = str(funct(*args,**kwargs))
        return "<h3>"+input+"</h3>"
    return wrapper

@bold
@h3
def example(*args):
    print "you entered:",str(args[0])
    return args[0]

Note : In both instances (example within and without decorators) the following output is achieved,

>>> example(1234)
you entered: 1234
'<h3><b>1234</b></h3>'

 

Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial