fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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>'

 

Tags: Python

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001