-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorators_example.py
107 lines (71 loc) · 1.82 KB
/
decorators_example.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# Decorators
# Everything in python is an object
# That means functions can be used as objects
# A decorator takes in a function, adds some functionality and returns it.
# Basic Decorator
def test_decorator(func):
print('before')
func()
print('after')
@test_decorator
def do_stuff():
print("Doing stuff")
# Real Decorator
# In this example we will change the functionality
def make_bold(func):
def inner():
print('<b>')
func()
print('</b>')
return inner
@make_bold
def print_name():
print('Alton')
print_name()
# Decorator with params
# Notice this has a defined number of parameters
def num_check(func):
def check_int(o):
if isinstance(0, int):
if o == 0:
print('Can not divide by zero')
return False
return True
print('f{o} is not a number')
return False
def inner(x, y):
if not check_int(x) or not check_int(y):
return
return func(x, y)
return inner
@num_check
def divide(a, b):
print(a / b)
divide(100, 3)
divide(0, 2)
# divide(100, 'cat')
# Decorator with unknown number of params
# We want a decorator that can pass params and handle anything
# We also want to chain them together
# *args **kwargs to the rescue
def outline(func):
def inner(*args, **kwargs):
print('-' * 20)
func(*args, **kwargs)
print(f'-' * 20)
return inner
def list_items(func):
def inner(*args, **kwargs):
func(*args, **kwargs)
print(f'args = {args}')
print(f'kwargs = {kwargs}')
for x in args:
print(f'arg={x}')
for k, v in kwargs.items():
print(f'key={k},value={v}')
return inner
@outline # this is run first
@list_items
def display(msg):
print(msg)
display("hello")