Some suggestions for using Python decorators

Source: Internet
Author: User

Some suggestions for using Python decorators

This article mainly introduces some suggestions for using the Python decorators. The decorators are an important part of Python learning. For more information, see

Basic decorator concepts

As we all know, the decorator is a well-known design model and is often used in AOP (cross-section programming) scenarios. It is more classic in terms of log insertion, performance testing, and transaction processing, web permission verification and Cache.

The Python language provides the decorator syntax (@). The typical decorator implementation is as follows:

?

1

2

3

@ Function_wrapper

Def function ():

Pass

@ Actually, it is the syntactic sugar proposed by python2.4. For python2.4 earlier versions, there is another equivalent implementation:

?

1

2

3

4

Def function ():

Pass

 

Function = function_wrapper (function)

Two implementations of the decorator

Function wrapper-classic implementation

?

1

2

3

4

5

6

7

8

Def function_wrapper (wrapped ):

Def _ wrapper (* args, ** kwargs ):

Return wrapped (* args, ** kwargs)

Return _ wrapper

 

@ Function_wrapper

Def function ():

Pass

Package-easy to understand

?

1

2

3

4

5

6

7

8

9

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

Function Introspection

When talking about a function, we usually want its attributes to be clearly defined as described in the document, such as _ name _ and _ doc __.

The attributes of a function are changed when the decorator is applied to a function, but this is not what we expect.

?

1

2

3

4

5

6

7

8

9

10

11

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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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 obtain the parameters (argument) or source code of the encapsulated function, we cannot get the expected results.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Import inspect

 

Def function_wrapper (wrapped ):...

 

@ Function_wrapper

Def function (arg1, arg2): pass

 

>>> Print (inspect. getargspec (function ))

ArgSpec (args = [], varargs = 'args', keywords = 'kwargs ', ults = None)

 

>>> Print (inspect. getsource (function ))

@ Functools. wraps (wrapped)

Def _ wrapper (* args, ** kwargs ):

Return wrapped (* args, ** kwargs)

Packaging Method (@ classmethod)

When the package (@ function_wrapper) is applied to @ classmethod, the following exception is thrown:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

Class Class (object ):

@ Function_wrapper

@ Classmethod

Def cmethod (cls ):

Pass

 

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

File "<stdin>", line 3, in Class

File "<stdin>", line 2, in wrapper

File ".../functools. py", line 33, in update_wrapper

Setattr (wrapper, attr, getattr (wrapped, attr ))

AttributeError: 'classmethod' object has no attribute' _ module __'

Because the implementation of @ classmethod lacks certain attributes required by functools. update_wrapper. This is a bug in functools. update_wrapper in python2. version 3.2 has been fixed. For details, refer to http://bugs.python.org/issue3445.

However, another problem occurs during execution in python3:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

Class Class (object ):

@ Function_wrapper

@ Classmethod

Def cmethod (cls ):

Pass

 

>>> Class. cmethod ()

Traceback (most recent call last ):

File "classmethod. py", line 15, in <module>

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 encapsulated function (@ classmethod) can be called directly, but this is not necessarily the case. The encapsulated function may actually be a descriptor, which means that the function (descriptor) must be correctly bound to an instance for its call. For the Descriptor Definition, refer to https://docs.python.org/2/howto/descriptor.html.

Summary-simplicity does not mean correctness

Although the method used to implement the decorator is usually very simple, it does not mean that they must be correct and always work properly.

As we can see above, functools. wraps () can help us solve the _ name _ and _ doc _ problems, but it is helpless to obtain function parameters (argument) or source code.

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.