-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path07_decorators.py
90 lines (70 loc) · 1.78 KB
/
07_decorators.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import os
import sys
def new_decorator(func):
def wrapTheFunction():
print("before run func")
func()
print("after run func")
return wrapTheFunction
def function_requiring_decoration():
print("in function_requireing_decoration()")
function_requiring_decoration()
func_with_deco = new_decorator( function_requiring_decoration )
func_with_deco()
@new_decorator
def anotherFunction():
print("anotherFunction")
anotherFunction()
# >>> use functools.wraps
from functools import wraps
def newDecorator(inFunc):
@wraps(inFunc)
def wrapTheFunction():
print("before run inFunc")
inFunc()
print("after run inFunc")
return wrapTheFunction
@newDecorator
def function_requiring_decorator():
print("in function_requiring_decorator")
return 'a'
print(function_requiring_decorator.__name__)
# >>>
from functools import wraps
canRun = True
def decoratorName(f):
@wraps(f)
def decorated(*args, **kwargs):
if not canRun:
return "Will not run"
return f(*args, **kwargs)
return decorated
@decoratorName
def func():
return("in func")
canRun = True
print(func())
canRun = False
print(func())
# example 1. : 인증
from functools import wraps
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
# example 2. : Logging
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit
def addFunc(x):
return x+x
result = addFunc(10)