Repository navigation
Expand file tree
/
Copy pathdecorators.py
More file actions
77 lines (55 loc) · 1.68 KB
/
Copy pathdecorators.py
File metadata and controls
77 lines (55 loc) · 1.68 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
# -*- 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: %r" % locals()
result = a + b
# print "\tResult --> %r" % result
return result
def logged_func(func):
def logged(*args, **kwargs):
print "Function %r called" % func.__name__
if args:
print "\twith args: %r" % (args, )
if kwargs:
print "\twith kwargs: %r" % kwargs
result = func(*args, **kwargs)
print "\t Result --> %r" % 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 xrange(n))
sum2x = Memoize(sum2x)
import time
def timed_func(func):
def timed(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print "time expired: %s" % elapsed
return result
return timed
@timed_func
@Memoize
def sum2x(n):
return sum(2 * i for i in xrange(n))