Monday, 12 October 2015

DecoraToRS

Python makes creating and using decorators a bit cleaner and nicer for the programmer.
To decorate get_text we don't have to get_text = p_decorator(get_text)
Consider this example:
     a simple way of using decorator with the use of @ symbol to get_text

def p_decorate(func):
   def func_wrapper(name):
       return "<p>{0}</p>".format(func(name))
   return func_wrapper

@p_decorate
def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

print get_text("John")

# Outputs <p>lorem ipsum, John dolor sit amet
</p>

A much better approach would be to make our decorator useful for functions and methods alike.

Passing arguments to decorators

consider a example in which 3 decorators are used with same functionalities wrapping up  strings with different tags,we can do better for tat as like follows:

def tags(tag_name):
    def tags_decorator(func):
        def func_wrapper(name):
            return "<{0}>{1}</{0}>".format(tag_name, func(name))
        return func_wrapper
    return tags_decorator

@tags("p")
def get_text(name):
    return "Hello "+name

print get_text("John")

# Outputs <p>Hello John</p>

In this example,above tags is our decorator generator.

Decorators can give so much power and elegance to your program. In general, decorators are ideal for extending the behavior of functions that we don't want to modify. For a great list of useful decorators I suggest you check out the Python Decorator Library


No comments:

Post a Comment