Some suggestions for using the Python adorner

Source: Internet
Author: User
The basic concept of adorners

As you know, adorners are a well-known design pattern that is often used in AOP (aspect-oriented programming) scenarios, with more classic insert logs, performance tests, transaction processing, Web permissions checks, caches, and so on.

The Python language itself provides the adorner syntax (@), and the typical adorner implementation is as follows:

  @function_wrapper  def function ():    Pass

@ is actually python2.4 's proposed syntax sugar, there is another equivalent implementation for the previous version of python2.4:

  def function ():    pass  function = Function_wrapper (function)

Two kinds of implementations of adorners

Function Wrapper-Classic implementation

  def function_wrapper (wrapped):    def _wrapper (*args, **kwargs): Return      wrapped (*args, **kwargs)    return _wrapper   @function_wrapper  def function ():    Pass

Class wrapper-Easy to understand

  Class Function_wrapper (object):    def __init__ (self, wrapped):      self.wrapped = wrapped    def __call__ (self, * args, **kwargs):      return self.wrapped (*args, **kwargs)  @function_wrapper  def function ():    Pass

Functions (function) introspection

When we talk about a function, we usually want the properties of the function to be clearly defined, as described in its documentation, such as __name__ and __doc__.

When you apply adorners to a function, the properties of the function change, but this is not what we expect.

  def function_wrapper (wrapped):    def _wrapper (*args, **kwargs): Return      wrapped (*args, **kwargs)    return _wrapper   @function_wrapper  def function ():    pass   >>> print (function.__name__)  _ Wrapper

The Python standard library provides functools.wraps () to solve this problem.

  Import Functools   def function_wrapper (wrapped):    @functools. Wraps (wrapped)    def _wrapper (*args, **kwargs ):      return Wrapped (*args, **kwargs)    return _wrapper   @function_wrapper  def function ():    pass   >>> print (function.__name__)  function

However, when we want to get the parameter (argument) of the wrapper function or source code, we also can't get the result we want.

  Import Inspect   def function_wrapper (wrapped): ...  @function_wrapper  def function (Arg1, arg2): Pass   >>> print (Inspect.getargspec (function))  Argspec (args=[], varargs= ' args ', keywords= ' Kwargs ', defaults=none)  >>> print (Inspect.getsource ( function))    @functools. Wraps (wrapped)    def _wrapper (*args, **kwargs):      return Wrapped (*args, **kwargs)

Wrapper class method (@classmethod)

When the wrapper (@function_wrapper) is applied to @classmethod, the following exception will be thrown:

  Class Class (Object):    @function_wrapper    @classmethod    def cmethod (CLS):      pass   Traceback (most Recent call last):   file "
 
  
   
  ", line 1, in 
  
   
    
      File "
   
    
     
    ", line 3, in Class   File "
    
     
      
     ", line 2, in wrapper   File ".../functools.py", line at Update_wrapper    SetAttr ( Wrapper, attr, GetAttr (wrapped, attr))  attributeerror: ' Classmethod ' object has no attribute ' __module__ '
    
      
 
     
    
   
  

Because @classmethod is implemented, some of the properties required by Functools.update_wrapper are missing. This is the bug,3.2 version of Functools.update_wrapper in Python2 has been fixed, refer to http://bugs.python.org/issue3445.

However, under Python3, another problem arose:

  Class Class (Object):    @function_wrapper    @classmethod    def cmethod (CLS):      pass   >>> Class.cmethod ()   Traceback (most recent):   File ' classmethod.py ', line-in 
 
  
   
      Class.cmethod ()   File "classmethod.py", line 6, in _wrapper    return wrapped (*args, **kwargs)  TypeError: ' Classmethod ' object is not callable
 
  

This is because the wrapper determines that the packaged function (@classmethod) can be called directly, but the fact is not necessarily the case. The wrapped function may actually be a descriptor (descriptor), meaning that the function (descriptor) must be properly bound to an instance in order to make it callable. For the definition of descriptors, refer to https://docs.python.org/2/howto/descriptor.html.
Summary-simplicity does not mean that the right

Although the methods used by people to implement adorners are usually simple, this does not mean that they must be correct and always work correctly.

As we have seen above, functools.wraps () can help us solve __name__ and __doc__ problems, but it is useless to get the parameters (argument) or source code of the function.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.