-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.py
More file actions
58 lines (44 loc) · 1.3 KB
/
Copy pathdecorators.py
File metadata and controls
58 lines (44 loc) · 1.3 KB
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
""" Decorator Samples """
from functools import wraps
""" Simple Decorator: does not decorate functions with arguments """
def uppercase(func):
@wraps(func)
def wrapper():
return func().upper()
return wrapper
def underline(func):
@wraps(func)
def wrapper():
return f"<u>{func()}</u>"
return wrapper
def emphasis(func):
@wraps(func)
def wrapper():
return f"<em>{func()}</em>"
return wrapper
# Those wraps decorators, are responsible for transmit function metadata to wrapped ones
# Metadata Like docstrings and name
""" Argument Decorator: Handle Args and Kwargs to wrapped functions """
def trace(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f'LOG: calling {func.__name__}() with {args}, {kwargs}')
original_result = func(*args, **kwargs)
print(f'LOG: {func.__name__}() returned {original_result!r}')
return original_result
return wrapper
"""
Multiple simple decorators usage.
Note that the activation order is bottom to top.
"""
@emphasis
@underline
@uppercase
def hello_world():
return f"Hello World!"
@trace
def hello_date(day, month, year):
return f"Hello, it's {day} of {month} from {year}!"
if __name__ == "__main__":
print(hello_world())
print(hello_date('friday', 'may', 2019))