-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdecorators.py
More file actions
76 lines (58 loc) · 1.81 KB
/
decorators.py
File metadata and controls
76 lines (58 loc) · 1.81 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# -*- coding: utf-8 -*-
def substitute(a_function):
"""return a different function than the one supplied"""
def new_function(*args, **kwargs):
return "I'm not that other function"
return new_function
def add(a, b):
print("Function 'add' called with args: {}, {}".format(a, b) )
result = a + b
print("\tResult --> {}".format(result))
return result
def logged_func(func):
def logged(*args, **kwargs):
print("Function {} called".format(func.__name__))
if args:
print("\twith args: {}".format(args))
if kwargs:
print("\twith kwargs: {}".format(kwargs))
result = func(*args, **kwargs)
print("\t Result --> {}".format(result))
return result
return logged
def simple_add(a, b):
return a + b
class Memoize(object):
"""
memoize decorator from avinash.vora
http://avinashv.net/2008/04/python-decorators-syntactic-sugar/
"""
def __init__(self, function): # runs when memoize class is called
self.function = function
self.memoized = {}
def __call__(self, *args): # runs when memoize instance is called
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*args)
return self.memoized[args]
@Memoize
def sum2x(n):
return sum(2 * i for i in range(n))
# sum2x = Memoize(sum2x)
@Memoize
def prod2(a,b):
return sum( a * b**2 for a,b in zip(range(a), range(b)))
import time
def timed_func(func):
def timed(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print("time expired: {}".format(elapsed))
return result
return timed
@timed_func
@Memoize
def sum2x(n):
return sum(2 * i for i in range(n))