Python decorator

The best time to plant a tree is ten years ago, followed by now!

As a script kid, I used to write scripts on weekdays, and I am not used to writing project-type code. However, in order to improve the quality of the code, improve the ability to encode, recently began to try to learn some advanced programming usage, this chapter is used to record some basic usage of python decorator, welcome to correct.

Decorator mode has many classic usage scenarios, such as inserting logs, performance testing, transaction processing, etc. With the decorator, you can extract a lot of similar functions in the function that are independent of its function, so as to achieve code reuse. In simple terms, the decorator is characterized by receiving functions as arguments and then returning functions.

getting Started

1
2
3
4
5
6
7
8
def log(func):
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
@log #now = log(now)
def now():
print '2013-12-25'

run:

1
2
3
>>> now()
call now():
2013-12-25

Implementation process description:

@log is equivalent to now=log(now), the original now function is still there, but now the now variable points to the new function. So when we run now(), instead of running the now function, we run the function returned by log(now), the warpper function. After running the warpper function, it will output call…., then execute func(args, **kwargs), and func is the incoming function now, so the now function is executed, ie now(args, *kwargs), Enter 2013-12-25, so that you don’t have to modify the now function to output the content before executing the now function.

Advanced

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#! -*- coding:utf-8 -*-
import functools
def log(*args):
if len(args)>0:
text=args[0]
else:
text=""
def a(func):
@functools.wraps(func) #run function attribute is assigned to b function. If not, the last run.__name__ output should be b instead of run
def b(*args,**kwargs):
Print "begin start", text #Execute the output before the run function
func(*args,**kwargs)
Print "end" #output after executing the run function
return b
return a
@log('nmask') #or @log() Supports indefinite parameters
Def run(*args,**kwargs): ##supports indefinite parameters
for i in args:
print i
run(1,2,3)
Print run.__name__ #run variable function name behind the variable

run:

1
2
3
4
5
6
begin start nmask
1
2
3
end
run

The log function is a decorator function, and the run function is a normal function.

  • @log is equivalent to run=log(run)
  • @log() is equivalent to run=log()(run)
  • @log(“test”) is equivalent to run=log(“test”)(run)

Implementation process description:

When executing the run(1,2,3) function, the log(‘test’) function is executed first, and a is returned, then a(run) is executed, b function is returned, and b is copied to run and executed. Run(1,2,3), actually executes b(1,2,3), first outputs begin start, then executes run(1,2,3) (the real run function), and outputs 1, 2, 3, Finally output end.

Instance Demo

Enter the current time:

1
2
3
4
5
6
7
8
9
10
11
12
13
def current_time(func):
'''
Output current time decorator
'''
def wrapper(*args,**kw):
print_time=time.strftime(ISOTIMEFORMAT,time.localtime())
print "%s[Log_Info]Nowtime is:%s%s" % (BLUE,print_time,END)
func(*args,**kw)
print_time=time.strftime(ISOTIMEFORMAT,time.localtime())
print "%s[Log_Info]Nowtime is:%s%s" % (BLUE,print_time,END)
print "---------------------------------"
return wrapper

Add a coroutine to the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def gevent_wrapper (* args):
'''
Turn a single-threaded program into a coroutine concurrent decorator
'''
import
from gevent import monkey,pool;monkey.patch_all()
import functools
Target_list=args[0] #to-be-detected target list
def run(func):
@functools.wraps(func)
def wrapper(*args,**kw):
tasks = [p.spawn(func,*args,**kw) for i in target_list]
gevent.joinall(tasks)
return wrapper
return run

Reference: [decorator | Liao Xuefeng] (http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000#0) Recommend novices to learn!

本文标题:Python decorator

文章作者:nmask

发布时间:2017年04月07日 - 10:04

最后更新:2019年07月11日 - 17:07

原始链接:https://thief.one/2017/04/07/Python decorator/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: