Skip to content

Commit bf75f9b

Browse files
committed
fix: decorator definition and example
1 parent d697a3d commit bf75f9b

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

  • src/8_compound_statements/8.7._function_definitions
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
def decorators:
3+
- formal: 𝑓: 𝑓 ↦ any
4+
5+
- in words: a high order function to modify and execute functions/methods
6+
7+
- plain english: syntactic sugar for invoking a high order function directly and returning the parameter function's result.
8+
9+
- intuition: ???
10+
11+
- properties:
12+
- specification: https://peps.python.org/pep-0318/
13+
14+
- examples:
15+
- see function runtime tracker below: def timed
16+
17+
- use cases:
18+
- aspect orientated programming:
19+
- logging
20+
21+
- proof: ???
22+
23+
References: ???
24+
"""
25+
26+
import time
27+
28+
29+
def timed(func):
30+
def function_executor(*args, **kwargs):
31+
print(f"Executing Function: {func.__name__} ")
32+
start = time.time()
33+
result = func(*args, **kwargs)
34+
end = time.time()
35+
print(
36+
f"Function: {func.__name__} took {(end - start)*1000} miliseconds to complete."
37+
)
38+
return result
39+
40+
return function_executor
41+
42+
43+
@timed
44+
def square(numbers):
45+
result = []
46+
for num in numbers:
47+
result.append(num * num)
48+
return result
49+
50+
51+
@timed
52+
def square_map_implementation(numbers):
53+
return list(map(lambda i: i * i, numbers))
54+
55+
56+
if __name__ == "__main__":
57+
numbers = [i for i in range(10)]
58+
print(square(numbers))
59+
print(square_map_implementation(numbers))
60+
61+
# direct invocation
62+
square_decorated = timed(square)
63+
print(square_decorated(numbers))

0 commit comments

Comments
 (0)