程式扎記: [ Python 文章收集 ] A guide to Python's function decorators

標籤

2016年6月6日 星期一

[ Python 文章收集 ] A guide to Python's function decorators

Source From Here 
Introduction 
Python is rich with powerful features and expressive syntax. One of my favorites is decorators. In the context of design patterns, decorators dynamically alter the functionality of a function, method or class without having to directly use subclasses. This is ideal when you need to extend the functionality of functions that you don't want to modify. We can implement the decorator pattern anywhere, but Python facilitates the implementation by providing much more expressive features and syntax for that. 

In this post I will be discussing Python's function decorators in depth, accompanied by a bunch of examples on the way to clear up the concepts. All examples are in Python 2.7 but the same concepts should apply to Python 3 with some change in the syntax. Essentially, decorators work as wrappers, modifying the behavior of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it. 

What you need to know about functions 
Before diving in, there are some prerequisites that should be clear. In Python, functions are first class citizens, they are objects and that means we can do a lot of useful stuff with them. 

- Assign functions to variables 
  1. def greet(name):  
  2.     return "hello "+name  
  3.   
  4. greet_someone = greet  
  5. print greet_someone("John")  
  6.   
  7. # Outputs: hello John  
- Define functions inside other functions 
  1. def greet(name):  
  2.     def get_message():  
  3.         return "Hello "  
  4.   
  5.     result = get_message()+name  
  6.     return result  
  7.   
  8. print greet("John")  
  9.   
  10. # Outputs: Hello John  
- Functions can be passed as parameters to other functions 
  1. def greet(name):  
  2.    return "Hello " + name   
  3.   
  4. def call_func(func):  
  5.     other_name = "John"  
  6.     return func(other_name)    
  7.   
  8. print call_func(greet)  
  9.   
  10. # Outputs: Hello John  
- Functions can return other functions 
In other words, functions generating other functions. 
  1. def compose_greet_func():  
  2.     def get_message():  
  3.         return "Hello there!"  
  4.   
  5.     return get_message  
  6.   
  7. greet = compose_greet_func()  
  8. print greet()  
  9.   
  10. # Outputs: Hello there!  
- Inner functions have access to the enclosing scope 
More commonly known as a closure. A very powerful pattern that we will come across while building decorators. Another thing to note, Python only allows read access to the outer scope and not assignment. Notice how we modified the example above to read a "name" argument from the enclosing scope of the inner function and return the new function. 
  1. def compose_greet_func(name):  
  2.     def get_message():  
  3.         return "Hello there "+name+"!"  
  4.   
  5.     return get_message  
  6.   
  7. greet = compose_greet_func("John")  
  8. print greet()  
  9.   
  10. # Outputs: Hello there John!  
Composition of Decorators 
Function decorators are simply wrappers to existing functions. Putting the ideas mentioned above together, we can build a decorator. Let's consider a function that wraps the string output of another function by p tags. 
  1. def get_text(name):  
  2.    return "lorem ipsum, {0} dolor sit amet".format(name)  
  3.   
  4. def p_decorate(func):  
  5.    def func_wrapper(name):  
  6.        return "{0}
    "
    .format(func(name))  
  7.    return func_wrapper  
  8.   
  9. my_get_text = p_decorate(get_text)  
  10.   
  11. print my_get_text("John")  
  12.   
  13. # Outputs lorem ipsum, John dolor sit amet
      
That was our first decorator. A function that takes another function as an argument, generates a new function, augmenting the work of the original function, and returning the generated function so we can use it anywhere. To have get_text itself be decorated by p_decorate, we just have to assign get_text to the result of p_decorate
  1. get_text = p_decorate(get_text)  
  2.   
  3. print get_text("John")  
  4.   
  5. # Outputs lorem ipsum, John dolor sit amet  
Another thing to notice is that our decorated function takes a name argument. All what we had to do in the decorator is to let the wrapper of get_text pass that argument. 

Python's Decorator Syntax 
Python makes creating and using decorators a bit cleaner and nicer for the programmer through some syntactic sugar To decorate get_text we don't have to get_text = p_decorator(get_text) There is a neat shortcut for that, which is to mention the name of the decorating function before the function to be decorated. The name of the decorator should be perpended with an @ symbol. 
  1. def p_decorate(func):  
  2.    def func_wrapper(name):  
  3.        return "{0}
    "
    .format(func(name))  
  4.    return func_wrapper  
  5.   
  6. @p_decorate  
  7. def get_text(name):  
  8.    return "lorem ipsum, {0} dolor sit amet".format(name)  
  9.   
  10. print get_text("John")  
  11.   
  12. # Outputs lorem ipsum, John dolor sit amet
      
Now let's consider we wanted to decorate our get_text function by 2 other functions to wrap a div and strong tag around the string output. 
  1. def p_decorate(func):  
  2.    def func_wrapper(name):  
  3.        return "{0}
    "
    .format(func(name))  
  4.    return func_wrapper  
  5.   
  6. def strong_decorate(func):  
  7.     def func_wrapper(name):  
  8.         return "{0}".format(func(name))  
  9.     return func_wrapper  
  10.   
  11. def div_decorate(func):  
  12.     def func_wrapper(name):  
  13.         return "
    {0}
    "
    .format(func(name))  
  14.     return func_wrapper  
With the basic approach, decorating get_text would be along the lines of 
  1. get_text = div_decorate(p_decorate(strong_decorate(get_text)))  
With Python's decorator syntax, same thing can be achieved with much more expressive power. 
  1. @div_decorate  
  2. @p_decorate  
  3. @strong_decorate  
  4. def get_text(name):  
  5.    return "lorem ipsum, {0} dolor sit amet".format(name)  
  6.   
  7. print get_text("John")  
  8.   
  9. # Outputs
    lorem ipsum, John dolor sit amet
      
Decorating Methods 
In Python, methods are functions that expect their first parameter to be a reference to the current object. We can build decorators for methods the same way, while taking self into consideration in the wrapper function. 
  1. def p_decorate(func):  
  2.    def func_wrapper(self):  
  3.        return "{0}
    "
    .format(func(self))  
  4.    return func_wrapper  
  5.   
  6. class Person(object):  
  7.     def __init__(self):  
  8.         self.name = "John"  
  9.         self.family = "Doe"  
  10.   
  11.     @p_decorate  
  12.     def get_fullname(self):  
  13.         return self.name+" "+self.family  
  14.   
  15. my_person = Person()  
  16. print my_person.get_fullname()  
A much better approach would be to make our decorator useful for functions and methods alike. This can be done by putting *args and **kwargs as parameters for the wrapper, then it can accept any arbitrary number of arguments and keyword arguments. 
  1. def p_decorate(func):  
  2.    def func_wrapper(*args, **kwargs):  
  3.        return "{0}
    "
    .format(func(*args, **kwargs))  
  4.    return func_wrapper  
  5.   
  6. class Person(object):  
  7.     def __init__(self):  
  8.         self.name = "John"  
  9.         self.family = "Doe"  
  10.   
  11.     @p_decorate  
  12.     def get_fullname(self):  
  13.         return self.name+" "+self.family  
  14.   
  15. my_person = Person()  
  16.   
  17. print my_person.get_fullname()  
Passing arguments to decorators 
Looking back at the example before the one above, you can notice how redundant the decorators in the example are. 3 decorators(div_decorate, p_decorate, strong_decorate) each with the same functionality but wrapping the string with different tags. We can definitely do much better than that. Why not have a more general implementation for one that takes the tag to wrap with as a string? Yes please! 
  1. def tags(tag_name):  
  2.     def tags_decorator(func):  
  3.         def func_wrapper(name):  
  4.             return "<{0}>{1}</{0}>".format(tag_name, func(name))  
  5.         return func_wrapper  
  6.     return tags_decorator  
  7.   
  8. @tags("p")  
  9. def get_text(name):  
  10.     return "Hello "+name  
  11.   
  12. print get_text("John")  
  13.   
  14. # Outputs Hello John
      
It took a bit more work in this case. Decorators expect to receive a function as an argument, that is why we will have to build a function that takes those extra arguments and generate our decorator on the fly. In the example abovetags, is our decorator generator

Debugging decorated functions 
At the end of the day decorators are just wrapping our functions, in case of debugging that can be problematic since the wrapper function does not carry the name, module and docstring of the original function. Based on the example above if we do: 
  1. print get_text.__name__  
  2. # Outputs func_wrapper  
The output was expected to be get_text yet, the attributes __name____doc__, and __module__ (Check types and members) of get_text got overridden by those of the wrapper as func_wrapper. Obviously we can re-set them withinfunc_wrapper but Python provides a much nicer way. 

Functools to the rescue 
Fortunately Python (as of version 2.5) includes the functools module which contains functools.wraps. Wraps is a decorator for updating the attributes of the wrapping function(func_wrapper) to those of the original function(get_text). This is as simple as decorating func_wrapper by @wraps(func). Here is the updated example: 
  1. from functools import wraps  
  2.   
  3. def tags(tag_name):  
  4.     def tags_decorator(func):  
  5.         @wraps(func)  
  6.         def func_wrapper(name):  
  7.             return "<{0}>{1}</{0}>".format(tag_name, func(name))  
  8.         return func_wrapper  
  9.     return tags_decorator  
  10.   
  11. @tags("p")  
  12. def get_text(name):  
  13.     """returns some text"""  
  14.     return "Hello "+name  
  15.   
  16. print get_text.__name__ # get_text  
  17. print get_text.__doc__ # returns some text  
  18. print get_text.__module__ # __main__  
You can notice from the output that the attributes of get_text are the correct ones now. 

Where to use decorators 
The examples in this post are pretty simple relative to how much you can do with decorators. They 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

More reading resources 
What is a decorator? 
Decorators I: Introduction to Python Decorators 
Python Decorators II: Decorator Arguments 
Python Decorators III: A Decorator-Based Build System 
Guide to: Learning Python Decorators by Matt Harrison

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!